处理 numpy 高级索引时出现奇怪的结果。这是一个错误还是 numpy 的约束?
>>> a = np.arange(9).reshape((3,3,))
>>> a[0,1] # OK
1
>>> a[[0,1]] # OK
array([[0, 1, 2],
[3, 4, 5]])
>>> a[[[0,1]]] # ? (the result is 2-dim instead of 3-dim. just as same as a[[0,1]]. )
array([[0, 1, 2],
[3, 4, 5]])
>>> a[[[[0,1]]]] # ?
array([[[0, 1, 2],
[3, 4, 5]]])
我也尝试过以下方法,没问题。
>>> a[[[0,1]],] # OK
array([[[0, 1, 2],
[3, 4, 5]]])
最佳答案
在当前版本中,1.18
:
In [13]: a[[[0,1]]]
/usr/local/bin/ipython3:1: FutureWarning: Using a non-tuple sequence
for multidimensional indexing is deprecated; use `arr[tuple(seq)]`
instead of `arr[seq]`. In the future this will be interpreted as an
array index, `arr[np.array(seq)]`, which will result either in an
error or a different result.
#!/usr/bin/python3
Out[13]:
array([[0, 1, 2],
[3, 4, 5]])
In [14]: a[np.array([[0,1]])]
Out[14]:
array([[[0, 1, 2],
[3, 4, 5]]])
In [15]: _.shape
Out[15]: (1, 2, 3)
换句话说,以前的版本将[13]解释为
In [16]: a[([0,1],)]
Out[16]:
array([[0, 1, 2],
[3, 4, 5]])
In [17]: _.shape
Out[17]: (2, 3)
In [18]: a[([[0,1]],)].shape
Out[18]: (1, 2, 3)
Numpy 一直在慢慢清理索引边缘情况,这很大程度上是多年前合并几个不同数字包的结果。
===
您的评论案例以可读形式呈现:
In [19]: a[[0,1],[0,1]]
Out[19]: array([0, 4])
In [20]: a[[[0,1],[0,1]]]
/usr/local/bin/ipython3:1: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
#!/usr/bin/python3
Out[20]: array([0, 4])
In [21]: a[([0,1],[0,1])]
Out[21]: array([0, 4])
In [22]: a[[[[0,1],[0,1]]]]
/usr/local/bin/ipython3:1: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
#!/usr/bin/python3
Out[22]:
array([[[0, 1, 2],
[3, 4, 5]],
[[0, 1, 2],
[3, 4, 5]]])
In [23]: a[np.array([[[0,1],[0,1]]])]
Out[23]:
array([[[[0, 1, 2],
[3, 4, 5]],
[[0, 1, 2],
[3, 4, 5]]]])
关于python - 这是 numpy 高级索引的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61180109/