How to mix numpy slices to list of indices?

2024/10/12 0:30:23

I have a numpy.array, called grid, with shape:

grid.shape = [N, M_1, M_2, ..., M_N]

The values of N, M_1, M_2, ..., M_N are known only after initialization.

For this example, let's say N=3 and M_1 = 20, M_2 = 17, M_3 = 9:

grid = np.arange(3*20*17*9).reshape(3, 20, 17, 9)

I am trying to loop over this array, as follows:

for indices, val in np.ndenumerate(grid[0]):print indices_some_func_with_N_arguments(*grid[:, indices])

At the first iteration, indices = (0, 0, 0) and:

grid[:, indices] # array with shape 3,3,17,9

whereas I want it to be an array of three elements only, much like:

grid[:, indices[0], indices[1], indices[2]] # array([   0, 3060, 6120])

which however I cannot implement like in the above line, because I don't know a-priori what is the length of indices.

I am using python 2.7, but a version-agnostic implementation is welcome :-)

Answer

I think you want something like this:

In [134]: x=np.arange(24).reshape(4,3,2)In [135]: x
Out[135]: 
array([[[ 0,  1],[ 2,  3],[ 4,  5]],[[ 6,  7],[ 8,  9],[10, 11]],[[12, 13],[14, 15],[16, 17]],[[18, 19],[20, 21],[22, 23]]])In [136]: for i,j in np.ndindex(x[0].shape):...:     print(i,j,x[:,i,j])...:     
(0, 0, array([ 0,  6, 12, 18]))
(0, 1, array([ 1,  7, 13, 19]))
(1, 0, array([ 2,  8, 14, 20]))
(1, 1, array([ 3,  9, 15, 21]))
(2, 0, array([ 4, 10, 16, 22]))
(2, 1, array([ 5, 11, 17, 23]))

where the 1st line is:

In [142]: x[:,0,0]
Out[142]: array([ 0,  6, 12, 18])

Unpacking the index tuple as i,j and using that in x[:,i,j] is the simplest way of doing this index. But to generalize it to other numbers of dimensions I'll have to play with tuples a bit. x[i,j] is the same as x[(i,j)].

In [147]: for ind in np.ndindex(x.shape[1:]):...:     print(ind,x[(slice(None),)+ind])...:     
((0, 0), array([ 0,  6, 12, 18]))
((0, 1), array([ 1,  7, 13, 19]))
...

with enumerate:

for ind,val in np.ndenumerate(x[0]):print(ind,x[(slice(None),)+ind])
https://en.xdnf.cn/q/118261.html

Related Q&A

Visualize strengths and weaknesses of a sample from pre-trained model

Lets say Im trying to predict an apartment price. So, I have a lot of labeled data, where on each apartment I have features that could affect the price like:city street floor year built socioeconomic s…

Scrapy get result in shell but not in script

one topic again ^^ Based on recommendations here, Ive implemented my bot the following and tested it all in shell :name_list = response.css("h2.label.title::text").extract()packaging_list = r…

How to find a source when a website uses javascript

What I want to achieve I am trying to scrape the website below using Beautiful-soup and when I load the page it does not give the table that shows various quotes. In my previous posts folks have helped…

How to print a list of dicts as an aligned table?

So after going through multiple questions regarding the alignment using format specifiers I still cant figure out why the numerical data gets printed to stdout in a wavy fashion.def create_data(soup_ob…

abstract classes in python: Enforcing type

My question is related to this question Is enforcing an abstract method implementation unpythonic? . I am using abstract classes in python but I realize that there is nothing that stops the user from …

Convert image array to original svs format

Im trying to apply a foreground extraction to a SVS image (Whole Slide Image) usign OpenSlide library.First, I converted my image to an array to work on my foreground extraction:image = np.asarray(oslI…

Printing bytestring via variable

I have the following Unicode text stored in variable:myvariable = Gen\xe8veWhat I want to do is to print myvariable and show this:GenveI tried this but failed:print myvariable.decode(utf-8)Whats the ri…

Loop and arrays of strings in python

I have the following data set:column1HL111 PG3939HL11 HL339PG RC--HL--PGI am attempting to write a function that does the following:Loop through each row of column1 Pull only the alphabet and put into…

2 Dendrograms + Heatmap from condensed correlationmatrix with scipy

I try to create something like this: plotting results of hierarchical clustering ontop of a matrix of data in pythonUnfortunatelly when I try to execute the code, I get the following warnings:Warning (…

Iterator example from Dive Into Python 3

Im learning Python as my 1st language from http://www.diveintopython3.net/. On Chp 7, http://www.diveintopython3.net/iterators.html, there is an example of how to use an iterator.import redef build_mat…