[英]mask a 2D numpy array based on values in one column
假设我有以下numpy数组:
a = [[1, 5, 6],
[2, 4, 1],
[3, 1, 5]]
我想掩盖第一列中有1
所有行。 那就是我想要的
[[--, --, --],
[2, 4, 1],
[3, 1, 5]]
这是否可以使用numpy蒙面数组操作? 怎么能这样做?
谢谢。
import numpy as np
a = np.array([[1, 5, 6],
[2, 4, 1],
[3, 1, 5]])
np.ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==1)).T)
# Returns:
masked_array(data =
[[-- -- --]
[2 4 1]
[3 1 5]],
mask =
[[ True True True]
[False False False]
[False False False]])
您可以通过创建所需的蒙版
mask = numpy.repeat(a[:,0]==1, a.shape[1])
和掩盖的数组
masked_a = numpy.ma.array(a, mask=numpy.repeat(a[:,0]==1, a.shape[1]))
您可以简单地创建一个空掩码,然后使用numpy-broadcasting(如@eumiro显示)但使用元素和按位“或”运算符|
:
>>> a = np.array([[1, 5, 6], [2, 4, 1], [3, 1, 5]])
>>> mask = np.zeros(a.shape, bool) | (a[:, 0] == 1)[:, None]
>>> np.ma.array(a, mask=mask)
masked_array(data =
[[-- -- --]
[2 4 1]
[3 1 5]],
mask =
[[ True True True]
[False False False]
[False False False]],
fill_value = 999999)
进一步解释:
>>> # select first column
>>> a[:, 0]
array([1, 2, 3])
>>> # where the first column is 1
>>> a[:, 0] == 1
array([ True, False, False], dtype=bool)
>>> # added dimension so that it correctly broadcasts to the empty mask
>>> (a[:, 0] == 1)[:, None]
array([[ True],
[False],
[False]], dtype=bool)
>>> # create the final mask
>>> np.zeros(a.shape, bool) | (a[:, 0] == 1)[:, None]
array([[ True, True, True],
[False, False, False],
[False, False, False]], dtype=bool)
这种方法的另一个优点是它不需要使用可能昂贵的乘法或np.repeat
所以它应该非常快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.