受这个问题启发,我正在尝试理解NumPy中的高级索引并建立更直观的理解。
我发现了一个有趣的案例。这是一个数组:
>>> 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]])
这看起来和我所在的位置不一致。这里的规则是什么?