Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing slice of 3D numpy array

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?

like image 316
Joe McG Avatar asked Jun 25 '15 22:06

Joe McG


3 Answers

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.

like image 51
hpaulj Avatar answered Sep 19 '22 15:09

hpaulj


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.

like image 35
fourwood Avatar answered Sep 20 '22 15:09

fourwood


Is this what you want?

arr.flatten()[123]
like image 45
ericthegreat Avatar answered Sep 17 '22 15:09

ericthegreat