2D Numpy Array花式索引+遮罩 [英] 2D Numpy Array Fancy Indexing + Masking
问题描述
我有:
import numpy as np
a = np.array([[ 4, 99, 2],
[ 3, 4, 99],
[ 1, 8, 7],
[ 8, 6, 8]])
为什么
a[[True, True, False, False], [1,2]]
等于
array([99, 99])
不是
array([99, 2],
[4, 99])
因为我要使用布尔掩码选择前两行,并使用花式索引选择第二和第三列?特别是在通话之后
Since I am selecting the first two rows using a boolean mask and the 2nd and 3rd columns using fancy indexing? Especially since calling
a[[True, True, False, False],:][:, [1,2]]
给了我我期望的结果.我猜想这是某种广播规则,但对我而言并不明显.谢谢!
gives me my expected result. Im guessing its some sort of broadcasting rule but it isn't apparent to me. Thanks!
推荐答案
布尔数组或列表的评估方式就像where
已将其转换为索引数组一样:
A boolean array or list evaluates as though where
had converted it to an index array:
In [285]: a[[True,True,False,False],[1,2]]
Out[285]: array([99, 99])
In [286]: a[np.where([True,True,False,False]),[1,2]]
Out[286]: array([[99, 99]])
In [287]: np.where([True,True,False,False])
Out[287]: (array([0, 1], dtype=int32),)
In [288]: a[[0,1], [1,2]]
Out[288]: array([99, 99])
这就是选择a[0,1]
和a[1,2]
,这是成对"选择.
So this is picking a[0,1]
and a[1,2]
, a 'pair-wise' selection.
该块用相互广播以产生(2,2)数组的数组(或等效列表)索引:
The block is indexed with arrays (or list equivalents) that broadcast against each other to produce a (2,2) array:
In [289]: a[np.ix_([0,1], [1,2])]
Out[289]:
array([[99, 2],
[ 4, 99]])
In [290]: a[[[0],[1]], [1,2]]
Out[290]:
array([[99, 2],
[ 4, 99]])
这种情况下相当于两个阶段的索引编制:a[[0,1],:][:,[1,2]]
This case is equivalent to a 2 stage indexing: a[[0,1],:][:,[1,2]]
我正在使用np版本12.在最近的发行版中,布尔值索引进行了一些更改.例如,如果布尔值的长度不正确,它将运行,但会发出警告(此部分是新的).
I'm using np version 12. There have been some changes in boolean index over the recent releases. For example, if the length of the boolean isn't right, it runs, but gives a warning (this part is new).
In [349]: a[[True,True,False],[1,2]]
/usr/local/bin/ipython3:1: VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 4 but corresponding boolean dimension is 3
#!/usr/bin/python3
Out[349]: array([99, 99])
第13版中的更改描述如下:
Changes for v 13 are described in:
https://docs.scipy.org /doc/numpy-dev/release.html#boolean-indexing-changes
这篇关于2D Numpy Array花式索引+遮罩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!