Numpy 通过两个掩码过滤二维数组
Numpy filter 2D array by two masks
我有一个二维数组和两个掩码,一个用于列,一个用于行。如果我尝试简单地执行 data[row_mask,col_mask]
,我会收到一条错误消息 shape mismatch: indexing arrays could not be broadcast together with shapes ...
。另一方面,data[row_mask][:,col_mask]
有效,但不那么漂亮。为什么它期望索引数组具有相同的形状?
这是一个具体的例子:
import numpy as np
data = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
row_mask = np.array([True, True, False, True])
col_mask = np.array([True, True, False])
print(data[row_mask][:,col_mask]) # works
print(data[row_mask,col_mask]) # error
使用ix_
函数:
>>> data[np.ix_(row_mask,col_mask)]
array([[ 1, 2],
[ 4, 5],
[10, 11]])
Combining multiple Boolean indexing arrays or a Boolean with an integer indexing array can best be understood with the obj.nonzero() analogy. The function ix_ also supports boolean arrays and will work without any surprises.
我有一个二维数组和两个掩码,一个用于列,一个用于行。如果我尝试简单地执行 data[row_mask,col_mask]
,我会收到一条错误消息 shape mismatch: indexing arrays could not be broadcast together with shapes ...
。另一方面,data[row_mask][:,col_mask]
有效,但不那么漂亮。为什么它期望索引数组具有相同的形状?
这是一个具体的例子:
import numpy as np
data = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
row_mask = np.array([True, True, False, True])
col_mask = np.array([True, True, False])
print(data[row_mask][:,col_mask]) # works
print(data[row_mask,col_mask]) # error
使用ix_
函数:
>>> data[np.ix_(row_mask,col_mask)]
array([[ 1, 2],
[ 4, 5],
[10, 11]])
Combining multiple Boolean indexing arrays or a Boolean with an integer indexing array can best be understood with the obj.nonzero() analogy. The function ix_ also supports boolean arrays and will work without any surprises.