Reputation: 167
I have a 3D numpy array of floating point numbers. Am I indexing the array improperly? I'd like to access slice 124 (index 123) but am seeing this error:
>>> arr.shape
(31, 285, 286)
>>> arr[:][123][:]
Runtime error
Traceback (most recent call last):
File "<string>", line 1, in <module>
IndexError: index 123 is out of bounds for axis 0 with size 31
What would be the cause of this error?
Upvotes: 8
Views: 17310
Reputation: 231335
arr[:][123][:]
is processed piece by piece, not as a whole.
arr[:] # just a copy of `arr`; it is still 3d
arr[123] # select the 123 item along the first dimension
# oops, 1st dim is only 31, hence the error.
arr[:, 123, :]
is processed as whole expression. Select one 'item' along the middle axis, and return everything along the other two.
arr[12][123]
would work, because that first select one 2d array from the 1st axis. Now [123]
works on that 285
length dimension, returning a 1d array. Repeated indexing [][]..
works just often enough to confuse new programmrs, but usually it is not the right expression.
Upvotes: 14
Reputation: 515
import numpy as np
s=np.ones((31,285,286)) # 3D array of size 3x3 with "one" values
s[:,123,:] # access index 123 as you want
Upvotes: 0
Reputation: 3707
Look up at some slice examples of a xD array. You can try this:
a[:,123,:]
Upvotes: 0
Reputation: 51
I think you might just want to do arr[:,123,:]
. That gives you a 2D array with a shape of (31, 286), with the contents of the 124th place along that axis.
Upvotes: 5