简体   繁体   English

Numpy:为什么使用列表和 numpy 数组对 > 2 维数组进行高级索引会给出不同的结果

[英]Numpy: Why advance indexing of > 2 dimensional arrays with a list and numpy array give different results

I have 3-dimensional numpy array我有 3 维 numpy 数组

a = np.array([
  [
    [1, 3],
    [0, 2]
  ], 
  [
    [2, 1],
    [4, 2]
  ]
], dtype=np.int32)

And I want to get the elements using the indices [0, 1, 1], and [1, 0, 1]我想使用索引 [0, 1, 1] 和 [1, 0, 1] 获取元素

which I expect to give me:我希望给我的:

[2, 1]

If I index with list, it returns the result I wanted, but if I index with Numpy array, it gives different results, why is that?如果我用列表索引,它会返回我想要的结果,但如果我用 Numpy 数组索引,它会给出不同的结果,这是为什么呢?

>>> indices = [[0, 1], [1, 0], [1, 1]]
>>> indices_arr = np.array(indices, dtype=np.int32)

>>> a[indices]
# OUTPUT
# array([2, 1], dtype=int32

>>> a[indices_arr]
# OUTPUT
'''
array([[[[1, 3],
         [0, 2]],

        [[2, 1],
         [4, 2]]],


       [[[2, 1],
         [4, 2]],

        [[1, 3],
         [0, 2]]],


       [[[2, 1],
         [4, 2]],

        [[2, 1],
         [4, 2]]]], dtype=int32)
'''

In a current numpy version indices gives a warning:在当前的 numpy 版本中, indices会发出警告:

In [46]: a[indices_arr].shape
Out[46]: (3, 2, 2, 2)

In [47]: a[indices]
C:\Users\paul\AppData\Local\Temp\ipykernel_8668\2035022355.py: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.
  a[indices]
Out[47]: array([2, 1])

doing the tuple conversion myself:自己进行元组转换:

In [48]: a[tuple(indices)]
Out[48]: array([2, 1])

Your indices_arr is the different result it warns about.您的indices_arr是它警告的不同结果。

With tuple, we are applying each sublist to a separate dimension of a`:使用tuple, we are applying each sublist to a separate dimension of

In [49]: a[[0, 1], [1, 0], [1, 1]]
Out[49]: array([2, 1])

With indices_arr , the array is applied to just the first dimension, hence the (2,) becomes (3,2).使用indices_arr ,数组仅应用于第一个维度,因此 (2,) 变为 (3,2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM