2

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
  • 1
    When you write myarray[:][:][0] do you actually mean myarray[:, :, 0]? The former is just equal to myarray[0], the latter is not. Commented Feb 25, 2016 at 14:53
  • (assuming you mean the latter, the question is a duplicate of stackoverflow.com/questions/12116830/…) Commented Feb 25, 2016 at 15:00

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

What if I want to call the i-th, not the last index?
if you don't know the shape of the array you can't know which item you want to get. you can't get a general index.
Look at np.take; it takes an axis parameter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.