访问3D numpy数组的切片

Joe*_*McG 6 python 3d numpy slice

我有一个3D numpy浮点数数组.我不正确地索引数组吗?我想访问片124(索引123),但我看到了这个错误:

>>> 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
Run Code Online (Sandbox Code Playgroud)

这个错误的原因是什么?

hpa*_*ulj 9

arr[:][123][:] 是一块一块地加工而不是整体加工.

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.
Run Code Online (Sandbox Code Playgroud)

arr[:, 123, :]被处理为整个表达式.沿中轴选择一个"项目",然后沿其他两个返回所有内容.

arr[12][123]会工作,因为首先从第一轴选择一个2d数组.现在[123]适用于该285长度维度,返回1d数组.重复索引的[][]..工作经常足以混淆新程序,但通常它不是正确的表达式.


小智 5

我想你可能只是想做arr[:,123,:]。这将为您提供一个形状为(31,286)的2D数组,其内容沿该轴位于第124位。