【发布时间】:2018-02-17 10:02:36
【问题描述】:
受this other question 的启发,我试图在 NumPy 中围绕advanced indexing 进行思考,并对其工作原理建立更直观的理解。
我发现了一个有趣的案例。这是一个数组:
>>> y = np.arange(10)
>>> y
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
如果我将它索引为标量,我当然会得到一个标量:
>>> y[4]
4
使用一维整数数组,我得到另一个一维数组:
>>> idx = [4, 3, 2, 1]
>>> y[idx]
array([4, 3, 2, 1])
所以如果我用一个二维整数数组索引它,我会得到......我会得到什么?
>>> idx = [[4, 3], [2, 1]]
>>> y[idx]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
哦不!对称性被打破。我必须用 3D 数组索引才能得到 2D 数组!
>>> idx = [[[4, 3], [2, 1]]]
>>> y[idx]
array([[4, 3],
[2, 1]])
是什么让 numpy 有这种行为?
为了让这更有趣,我注意到使用 numpy 数组(而不是列表)进行索引的行为符合我的直觉预期,而 2D 给了我 2D:
>>> idx = np.array([[4, 3], [2, 1]])
>>> y[idx]
array([[4, 3],
[2, 1]])
这看起来与我所在的位置不一致。这里有什么规则?
【问题讨论】:
-
我认为this might be a good point to start from,虽然我也不知所措地解释了这种行为
-
This 半小时前被问到,在这里似乎很相关。