访问 3D numpy 数组的切片

Accessing slice of 3D numpy array

我有一个浮点数的 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

这个错误的原因是什么?

这是你想要的吗?

arr.flatten()[123]

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

查看 xD 数组的一些切片示例。你可以试试这个:

a[:,123,:]

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

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.

arr[:, 123, :] 作为整个表达式处理。 Select 一个 'item' 沿中轴,return 沿其他两个。

arr[12][123] 会起作用,因为第一个 select 来自第一个轴的二维数组。现在 [123]285 长度维度上工作,returning 一维数组。重复索引 [][].. 的工作频率足以让新程序员感到困惑,但通常它不是正确的表达方式。