简体   繁体   English

Numpy:如何以矢量方式应用蒙版?

[英]Numpy: how do I apply masks vectorwise?

I have a numpy array that is a list of vectors, like我有一个 numpy 数组,它是一个向量列表,比如

arr1 = [ [ 1, 2 ], [ 2, 2 ], [ 5, 3 ], [ 9, -1 ], [ 6, 3 ], ... ]

corresponding to x,y value pairs.对应于 x,y 值对。 I would like to set up a mask using criteria for both the x and y components, for example 0 < x < 4 and 0 < y < 7, in such a way that the mask for the above looks like:我想使用 x 和 y 分量的标准设置一个掩码,例如 0 < x < 4 和 0 < y < 7,这样上面的掩码看起来像:

[ [ True, True ], [ True, True ], [ False, False ], [ False, False ], [ False, False ], ... ]

In other words, for each vector in the array, I want the mask to have the same truth value for both components, and only return True if the conditions for x and y are both satisfied.换句话说,对于数组中的每个向量,我希望掩码对两个分量都具有相同的真值,并且仅当 x 和 y 的条件都满足时才返回True I tried something like:我试过类似的东西:

masked = numpy.ma.array(arr1, mask= [0<arr1[:,0]<4 & 0<arr1[:,1]<7, 0<arr1[:,0]<4 & 0<arr1[:,1]<7])

But it tells me "The truth value of an array with more than one element is ambiguous."但它告诉我“具有多个元素的数组的真值是模棱两可的。” Is there a way to do this concisely without using loops or if elses?有没有办法在不使用循环或 if else 的情况下简洁地做到这一点?

Using the input array:使用输入数组:

print(arr1)
array([[ 1,  2],
       [ 2,  2],
       [ 5,  3],
       [ 9, -1],
       [ 6,  3]])

You can check for the conditions on each of the columns individually (do note that chained comparisons don't work in NumPy).您可以单独检查每列的条件(请注意, 链式比较在 NumPy 中不起作用)。 Then take the bitwise AND of both conditions and broadcast to the shape of the array:然后对两个条件进行按位与并广播到数组的形状:

x = arr1[:,0] 
y = arr1[:,1] 

c1 = (x>0)&(x<4)
c2 = (y>0)&(y<7)

np.broadcast_to((c1&c2)[:,None], arr1.shape)
array([[ True,  True],
       [ True,  True],
       [False, False],
       [False, False],
       [False, False]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM