【发布时间】:2021-03-17 08:59:40
【问题描述】:
我偶然发现了我认为 numpy 的一种奇怪(或至少不直观)的行为,我想了解它为什么会这样。 让我们生成一个形状为 (4, 3, 3) 的通用数组。
import numpy as np
arr = np.arange(4*3*3).reshape((4, 3, 3))
将 arr 视为四个 3×3 矩阵的列表,我现在想交换列表中第一个矩阵的前两列。我可以用索引列表重新排序列:
idx = np.array([1, 0, 2])
m = arr[0]
m[:, idx]
>>> array([[1, 0, 2],
[4, 3, 5],
[7, 6, 8]])
我看到我成功交换了两列。但是,如果我尝试直接用 arr 做同样的事情,我会得到:
arr[0, :, idx]
>>> array([[1, 4, 7],
[0, 3, 6],
[2, 5, 8]])
我想我做错了什么,但我不理解这种行为。
【问题讨论】:
-
你应该使用 arr[0][:,idx]
-
这是一个混合基本和高级索引的示例,如 numpy.org/doc/stable/reference/… 中所述。
:维度已移至末尾,转置结果。
标签: python arrays numpy indexing numpy-ndarray