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?
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.
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.
Is this what you want?
arr.flatten()[123]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With