Arrays Numpy二维数组布尔掩蔽

Arrays Numpy二维数组布尔掩蔽,arrays,numpy,indexing,Arrays,Numpy,Indexing,我不明白这其中的一个例子 那么为什么a[b1,b2]会返回数组([4,10])?它不应该返回数组([[4,6],[8,10]]) 任何详细的解释都将不胜感激 第一个数组的true索引为 >>> i = np.where(b1) >>> i array([1,2]) 对于第二个数组,它们是 >>> j = np.where(b2) >>> j array([0,1]) 将这些索引掩码一起使用 >>> a

我不明白这其中的一个例子

那么为什么
a[b1,b2]
会返回
数组([4,10])
?它不应该返回
数组([[4,6],[8,10]])


任何详细的解释都将不胜感激

第一个数组的true索引为

>>> i = np.where(b1)
>>> i 
array([1,2])
对于第二个数组,它们是

>>> j = np.where(b2)
>>> j
array([0,1])
将这些索引掩码一起使用

>>> a[i,j]
array([4, 10])

当您使用多个数组对数组进行索引时,它将使用索引数组中的元素对进行索引

>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> b1
array([False,  True,  True], dtype=bool)
>>> b2
array([ True, False,  True, False], dtype=bool)
>>> a[b1, b2]
array([ 4, 10])
请注意,这相当于:

>>> a[(1, 2), (0, 2)]
array([ 4, 10])
哪些是
a[1,0]
a[2,2]

>>> a[1, 0]
4
>>> a[2, 2]
10
由于这种成对行为,通常不能使用单独的长度数组进行索引(它们必须能够广播)。所以这个例子有点意外,因为两个索引数组都有两个索引,它们都是
True
;例如,如果其中一个有三个
True
值,您将得到一个错误:

>>> b3 = np.array([True, True, True, False])
>>> a[b1, b3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (3,)
否则,也可以将索引数组转换为与
a
形状相同的二维数组,但请注意,如果这样做,结果将是线性数组(因为可以拉出任意数量的元素,当然可能不是正方形):


在2D numpy数组上应用常规布尔2D掩码的另一种方法如下:

使用矩阵元素相乘:

import numpy as np

n = 100
mask = np.identity(n)
data = np.random.rand(n,n)

data_masked = data * mask
在这个随机示例中,只保留对角线上的元素掩模可以是任意n×n矩阵。

>>> a[b1][:, b2]
array([[ 4,  6],
       [ 8, 10]])
>>> a[np.outer(b1, b2)]
array([ 4,  6,  8, 10])
import numpy as np

n = 100
mask = np.identity(n)
data = np.random.rand(n,n)

data_masked = data * mask