为什么我们在Numpy中获得双布尔索引的结果? [英] Why do we get such a result for double boolean indexing in Numpy?
问题描述
我对最后一个表达式的结果感到惊讶?
I was surprised by the result of the last expression?
>>> from numpy import array, arange
>>> a = arange(12).reshape(3,4)
>>> b1 = array([False,True,True]) # first dim selection
>>> b2 = array([True,False,True,False]) # second dim selection
>>>
>>> a[b1,:] # selecting rows
array([[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>>
>>> a[b1] # same thing
array([[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>>
>>> a[:,b2] # selecting columns
array([[ 0, 2],
[ 4, 6],
[ 8, 10]])
>>>
>>> a[b1,b2] # a weird thing to do
array([ 4, 10])
我预计:
array([[ 4, 6],
[ 8, 10]])
你有什么解释为什么会这样吗?
Do you have any explanation why it is the case?
推荐答案
让我们从你的数组开始:
Let's start with your array:
a = np.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
您当前的索引逻辑等于以下内容:
Your current indexing logic equates to the following:
a[[1, 2], [0, 2]] # array([ 4, 10])
坚持2维,NumPy将其解释为索引dim1-indices [1,2]
和dim2-indices [0,2 ]
,或坐标(1,0)
和(2,2)
。此处不涉及广播。
Sticking to 2 dimensions, NumPy interprets this as indexing dim1-indices [1, 2]
and dim2-indices [0, 2]
, or coordinates (1, 0)
and (2, 2)
. There's no broadcasting involved here.
要允许使用布尔数组进行广播,您可以使用 numpy.ix _
:
To permit broadcasting with Boolean arrays, you can use numpy.ix_
:
res = a[np.ix_(b1, b2)]
print(res)
array([[ 4, 6],
[ 8, 10]])
魔法 ix _
执行记录在 docs :布尔序列将被解释为相应维度的布尔掩码(相当于传入 np.nonzero(boolean_sequence)
)。
The magic ix_
performs is noted in the docs: "Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equivalent to passing in np.nonzero(boolean_sequence)
)."
print(np.ix_(b1, b2))
(array([[1],
[2]], dtype=int64), array([[0, 2]], dtype=int64))
作为附注,如果你有整数索引,你可以使用更直接的方法:
As a side note, you can use a more direct approach if you have integer indices:
b1 = np.array([1, 2])
b2 = np.array([0, 2])
a[b1[:, None], b2]
参见:相关问题,说明为什么此方法不适用于布尔数组。
See also: related question on why this method does not work with Boolean arrays.
这篇关于为什么我们在Numpy中获得双布尔索引的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!