Accessing slice of 3D numpy array

14,165

Solution 1

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.

Solution 2

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.

Solution 3

Is this what you want?

arr.flatten()[123]
Share:
14,165
Joe McG
Author by

Joe McG

Updated on June 25, 2022

Comments

  • Joe McG
    Joe McG almost 2 years

    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?

  • o11c
    o11c almost 9 years
    I'm pretty sure this returns a single value, not a slice.
  • Joe McG
    Joe McG almost 9 years
    thanks! and thanks for the clarification on arr[:] being an initial copy of arr. I often forget that.