由两个遮罩组成的Numpy滤镜2D阵列 [英] Numpy filter 2D array by two masks
问题描述
我有一个2D数组和两个蒙版,一个用于列,一个用于行.如果我尝试简单地执行data[row_mask,col_mask]
,则会收到一条错误消息,提示shape mismatch: indexing arrays could not be broadcast together with shapes ...
.另一方面,data[row_mask][:,col_mask]
可以工作,但是不那么漂亮.为什么它期望索引数组具有相同的形状?
I have a 2D array and two masks, one for columns, and one for rows. If I try to simply do data[row_mask,col_mask]
, I get an error saying shape mismatch: indexing arrays could not be broadcast together with shapes ...
. On the other hand, data[row_mask][:,col_mask]
works, but is not as pretty. Why does it expect indexing arrays to be of the same shape?
这是一个具体示例:
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]])
使用 ix_ 也支持布尔数组并且将毫无意外地工作.
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.
这篇关于由两个遮罩组成的Numpy滤镜2D阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!