2
votes

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 myarray I can use myarray[:][:][0] because I know there are 3 dimensions (I use 3 pairs of []).

In case of 4 dimensions, I would use myarray[:][:][:][0]. 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.

2
When you write myarray[:][:][0] do you actually mean myarray[:, :, 0]? The former is just equal to myarray[0], the latter is not.Alex Riley
(assuming you mean the latter, the question is a duplicate of stackoverflow.com/questions/12116830/…)Alex Riley

2 Answers

4
votes

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

myarray[:,:,:,i]
myarray[:,2,:,:]
myarray[...,3]
myarray[...,3,:]

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
myarray[tuple(ind)]
# same as myarray[:,:,3,:]
# myarray.take(3, axis=2)

np.apply_along_axis performs this style of indexing.

e.g.

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)
0
votes

You can use:

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

print myarray[..., 0]

it will get the first item of the last index.