8

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?

5 Answers 5

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! and thanks for the clarification on arr[:] being an initial copy of arr. I often forget that.
5

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.

Comments

1

Is this what you want?

arr.flatten()[123]

1 Comment

I'm pretty sure this returns a single value, not a slice.
0

Look up at some slice examples of a xD array. You can try this:

a[:,123,:]

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.