1、取数
arr = np.arange(24).reshape(2, 4, 3)
arr
Out[52]:
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23]]])
从 array 中取单个元素,直接用下标作索引,比如 arr[2, 2, 2],或者切片 arr[1:2, :, :2]
arr[1, 2, 2]
Out[55]: 20
arr[1:2, :, :1]
Out[40]:
array([[[12],
[15],
[18],
[21]]])
要同时取多个元素,各个轴的下标要为 list
arr[1, [0, 2, 3], 0]
Out[62]: array([12, 18, 21])
2、IndexError 报错处理
但是,在多个轴上指定下标取元素,会导致 IndexError 错误
arr[1, [0, 2, 3], [0, 1]]
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-63-de270b09da4c>", line 1, in <module>
arr[1, [0, 2, 3], [0, 1]]
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,)
访问numpy多维数组时,用于索引的数组需要具有相同的形状(行和列)。
这样可分两步选择数组。
tmp1 = arr[1, [0, 2, 3], :]
res = tmp1[:, [0, 1]]
res
Out[74]:
array([[12, 13],
[18, 19],
[21, 22]])
参考资料:
1、python取array中指定元素
2、python Numpy 数组操作时报 “shape mismatch: indexing arrays could not be broadcast together with shapes” 错误的解决方案