Fidd Fidd -3 years ago 124
Python Question

Indexing ndarray of variable number of dimensions

I have an instance of numpy ndarray, but of a variable size.

import numpy as np
dimensions = (4, 4, 4)
myarray = np.zeros(shape = dimensions)

In this case, I get a "cubic" shape of the array and if I want to index a slice of
I can use
because I know there are 3 dimensions (I use 3 pairs of

In case of 4 dimensions, I would use
. But since the number of dimensions may change, I cannot hard-code it this way.

How can I index a slice of such an array depending on the number of dimensions? Seems like a simple problem, cannot think of any solution though.

Answer Source

You index myarray with 1 bracket set, not multiple ones:


One : for each dimension that you want all of. ... stands in for multiple : - provided numpy can clearly identify the number.

Trailing : can be omitted, except of course when using ....

take can be used in the same way; it accepts an axis parameter:

np.take(myarray, i, axis=3)

You can also construct the indexing as a tuple, e.g.

ind = [slice(None)]*4
ind[2] = 3
# same as myarray[:,:,3,:]
# myarray.take(3, axis=2)

np.apply_along_axis performs this style of indexing.


In [274]: myarray=np.ones((2,3,4,5))

In [275]: myarray[:,:,3,:].shape
Out[275]: (2, 3, 5)

In [276]: myarray.take(3,axis=2).shape
Out[276]: (2, 3, 5)

In [277]: ind=[slice(None)]*4; ind[2]=3

In [278]: ind
Out[278]: [slice(None, None, None), slice(None, None, None), 3, slice(None, None, None)]

In [279]: myarray[tuple(ind)].shape
Out[279]: (2, 3, 5)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download