问题描述
我正在使用一个 ndarray 来切片另一个 ndarray.通常我使用 arr[ind_arr]
.numpy
似乎不喜欢这个并引发了一个 FutureWarning: 不推荐使用非元组序列进行多维索引使用 arr[tuple(seq)] 而不是 arr[seq]
.
I am using an ndarray to slice another ndarray.Normally I use arr[ind_arr]
. numpy
seems to not like this and raises a FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use arr[tuple(seq)] instead of arr[seq]
.
arr[tuple(seq)]
和 arr[seq]
有什么区别?
关于 StackOverflow 的其他问题似乎在 scipy
和 pandas
中遇到了这个错误,并且大多数人建议错误出在这些包的特定版本中.我遇到了纯粹在 numpy
中运行的警告.
Other questions on StackOverflow seem to be running into this error in scipy
and pandas
and most people suggest the error to be in the particular version of these packages. I am running into the warning running purely in numpy
.
示例帖子:
FutureWarning:不推荐使用非元组序列进行多维索引,使用 `arr[tuple(seq)]` 而不是 `arr[seq]`
FutureWarning:不推荐使用非元组序列进行多维索引,使用 `arr[tuple(seq)]`
在 seaborn 中使用 distplot 的 FutureWarning
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
推荐答案
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_
做同样的事情,但返回一个元组:
ix_
does the same thing, but returns a tuple:
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
列表建立索引:
indexing with the meshgrid
list:
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
结果与解包一起使用:
Often the meshgrid
result is used with unpacking:
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)]
是一样的,构成了2个子数组的元组.
Here [I,J]
is the same as [(I,J)]
, making a tuple of the 2 subarrays.
基本上,他们试图消除由于历史原因而存在的漏洞.我不知道他们是否可以在不引起进一步兼容性问题的情况下更改 meshgrid
结果的处理.
Basically they are trying to remove a loophole that existed for historical reasons. I don't know if they can change the handling of meshgrid
results without causing further compatibility issues.
这篇关于`arr[tuple(seq)]` 和 `arr[seq]` 有什么区别?关于使用非元组序列进行多维索引已弃用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!