`arr [tuple(seq)]`和`arr [seq]`之间有什么区别?不建议使用将非元组序列用于多维索引

时间:2019-06-13 11:33:42

标签: numpy numpy-ndarray

我正在使用ndarray切片另一个ndarray。 通常我使用arr[ind_arr]numpy似乎不喜欢这样,并提出了FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use arr[tuple(seq)] instead of arr[seq]

arr[tuple(seq)]arr[seq]有什么区别?

scipypandas中,有关StackOverflow的其他问题似乎正在遇到此错误,并且大多数人都认为该错误与这些软件包的特定版本有关。我碰到了纯粹在numpy中运行的警告。

示例帖子:

FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use `arr[tuple(seq)]` instead of `arr[seq]`

FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use `arr[tuple(seq)]`

FutureWarning with distplot in seaborn

MWE复制警告:

import numpy as np

# generate a random 2d array
A = np.random.randint(20, size=(7,7))
print(A, '\n')

# define indices
ind_i = np.array([1, 2, 3])  # along i
ind_j = np.array([5, 6])  # along j

# generate index array using meshgrid
ind_ij = np.meshgrid(ind_i, ind_j, indexing='ij')

B = A[ind_ij]
print(B, '\n')

C = A[tuple(ind_ij)]
print(C, '\n')

# note: both produce the same result

1 个答案:

答案 0 :(得分:0)

meshgrid返回数组列表:

In [50]: np.meshgrid([1,2,3],[4,5],indexing='ij')                                                      
Out[50]: 
[array([[1, 1],
        [2, 2],
        [3, 3]]), array([[4, 5],
        [4, 5],
        [4, 5]])]
In [51]: np.meshgrid([1,2,3],[4,5],indexing='ij',sparse=True)                                          
Out[51]: 
[array([[1],
        [2],
        [3]]), array([[4, 5]])]

ix_做同样的事情,但是返回一个元组:

In [52]: np.ix_([1,2,3],[4,5])                                                                         
Out[52]: 
(array([[1],
        [2],
        [3]]), array([[4, 5]]))

np.ogrid也会产生列表。

In [55]: arr = np.arange(24).reshape(4,6)                                                              

使用ix元组建立索引:

In [56]: arr[_52]                                                                                      
Out[56]: 
array([[10, 11],
       [16, 17],
       [22, 23]])

使用meshgrid列表编制索引:

In [57]: arr[_51]                                                                                      
/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[57]: 
array([[10, 11],
       [16, 17],
       [22, 23]])

meshgrid结果通常与拆包一起使用:

In [62]: I,J = np.meshgrid([1,2,3],[4,5],indexing='ij',sparse=True)                                    
In [63]: arr[I,J]                                                                                      
Out[63]: 
array([[10, 11],
       [16, 17],
       [22, 23]])

这里[I,J][(I,J)]相同,组成了两个子数组的元组。

基本上,他们正试图消除由于历史原因而存在的漏洞。我不知道他们是否可以更改meshgrid结果的处理而不会引起进一步的兼容性问题。