由两个遮罩组成的Numpy滤镜2D阵列 [英] Numpy filter 2D array by two masks

查看:88
本文介绍了由两个遮罩组成的Numpy滤镜2D阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆