extract all vertical slices from numpy array

2024/11/19 12:31:53

I want to extract a complete slice from a 3D numpy array using ndeumerate or something similar.

arr = np.random.rand(4, 3, 3)

I want to extract all possible arr[:, x, y] where x, y range from 0 to 2

Answer

ndindex is a convenient way of generating the indices corresponding to a shape:

In [33]: arr = np.arange(36).reshape(4,3,3)
In [34]: for xy in np.ndindex((3,3)):...:     print(xy, arr[:,xy[0],xy[1]])...:     
(0, 0) [ 0  9 18 27]
(0, 1) [ 1 10 19 28]
(0, 2) [ 2 11 20 29]
(1, 0) [ 3 12 21 30]
(1, 1) [ 4 13 22 31]
(1, 2) [ 5 14 23 32]
(2, 0) [ 6 15 24 33]
(2, 1) [ 7 16 25 34]
(2, 2) [ 8 17 26 35]

It uses nditer, but doesn't have any speed advantages over a nested pair of for loops.

In [35]: for x in range(3):...:     for y in range(3):...:         print((x,y), arr[:,x,y])

ndenumerate uses arr.flat as the iterator, but using it to

In [38]: for xy, _ in np.ndenumerate(arr[0,:,:]):...:     print(xy, arr[:,xy[0],xy[1]])

does the same thing, iterating on the elements of a 3x3 subarray. As with ndindex it generates the indices. The element won't be the size 4 array that you want, so I ignored that.


A different approach is to flatten the later axes, transpose, and then just iterate on the (new) first axis:

In [43]: list(arr.reshape(4,-1).T)
Out[43]: 
[array([ 0,  9, 18, 27]),array([ 1, 10, 19, 28]),array([ 2, 11, 20, 29]),array([ 3, 12, 21, 30]),array([ 4, 13, 22, 31]),array([ 5, 14, 23, 32]),array([ 6, 15, 24, 33]),array([ 7, 16, 25, 34]),array([ 8, 17, 26, 35])]

or with the print as before:

In [45]: for a in arr.reshape(4,-1).T:print(a)
https://en.xdnf.cn/q/119955.html

Related Q&A

Output an OrderedDict to CSV

I read a CSV file and use the usaddress library to parse an address field. How do I write the resulting OrderedDicts to another CSV file?import usaddress import csvwith open(output.csv) as csvfile:re…

min() arg is an empty sequence

I created a function that consumes a list of values and produces the average. However it only works when I use integer values. I get the following error when I make the values into floats:min() arg is …

Removing last words in each row in pandas dataframe

A dataframe contains a column named full_name and the rows look like this: full_name Peter Eli Smith Vanessa Mary Ellen Raul Gonzales Kristine S Lee How do I remove the last words and add an additi…

Object of type function has no len() in python

I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.Here is the code that Ive wrote.def main():while True:userInput(…

My If condition within a while loop doesnt break the loop

Struggling to get my code for the final room to finish the text-based game assigned to me. I essentially want the player to be forced to get all 6 items prior to entry. Any help is greatly appreciated.…

Adding strings, first, first + second, etc

Program has to be able adding strings from the list and output them in sequence but in the way: 1 string 1 + 2 string 1 + 2 + 3 string ...def spacey(array):passe = ""i = ""m = []for…

Store Variables in Lists python

So I have tried to do this, and I think its clear what I want, I want to store the message variables that I have made in a List and then use this for printing, I wonder why does this not work?items = …

How can I kill the explorer.exe process?

Im writing a script which is meant to kill explorer.exe. I searched a bit about it and the best answer Ive seen uses the taskkill command. I tried it, but when I run it on my computer it says it worked…

A presence/activity set command?

So, I was wondering if there could be a command I could write that allows me to set the bots presence and activity (ex. ~~set presence idle or ~~set activity watching "people typing ~~help") …

Inverted Index in Python not returning desired results

Im having trouble returning proper results for an inverted index in python. Im trying to load a list of strings in the variable strlist and then with my Inverse index looping over the strings to return…