从数组中屏蔽特定值 [英] Mask out specific values from an array
问题描述
示例:
我有一个数组:
array([[1, 2, 0, 3, 4],
[0, 4, 2, 1, 3],
[4, 3, 2, 0, 1],
[4, 2, 3, 0, 1],
[1, 0, 2, 3, 4],
[4, 3, 2, 0, 1]], dtype=int64)
我有一组坏"值(可变长度,顺序无关紧要):
I have a set (variable length, order doesn't matter) of "bad" values:
{2, 3}
我想返回隐藏这些值的掩码:
I want to return the mask that hides these values:
array([[False, True, False, True, False],
[False, False, True, False, True],
[False, True, True, False, False],
[False, True, True, False, False],
[False, False, True, True, False],
[False, True, True, False, False]], dtype=bool)
在 NumPy 中执行此操作的最简单方法是什么?
What's the simplest way to do this in NumPy?
推荐答案
使用 np.in1d
为我们提供了这种匹配出现的扁平掩码,然后重新整形回所需输出的输入数组形状,就像这样 -
Use np.in1d
that gives us a flattened mask of such matching occurrences and then reshape back to input array shape for the desired output, like so -
np.in1d(a,[2,3]).reshape(a.shape)
请注意,我们需要以列表或数组的形式输入要搜索的数字.
Note that we need to feed in the numbers to be searched as a list or an array.
样品运行 -
In [5]: a
Out[5]:
array([[1, 2, 0, 3, 4],
[0, 4, 2, 1, 3],
[4, 3, 2, 0, 1],
[4, 2, 3, 0, 1],
[1, 0, 2, 3, 4],
[4, 3, 2, 0, 1]])
In [6]: np.in1d(a,[2,3]).reshape(a.shape)
Out[6]:
array([[False, True, False, True, False],
[False, False, True, False, True],
[False, True, True, False, False],
[False, True, True, False, False],
[False, False, True, True, False],
[False, True, True, False, False]], dtype=bool)
2018 版:numpy.isin
使用内置的 NumPy np.isin
(在 1.13.0
) 保持形状,因此不需要我们事后重塑 -
2018 Edition : numpy.isin
Use NumPy built-in np.isin
(introduced in 1.13.0
) that keeps the shape and hence doesn't require us to reshape afterwards -
In [153]: np.isin(a,[2,3])
Out[153]:
array([[False, True, False, True, False],
[False, False, True, False, True],
[False, True, True, False, False],
[False, True, True, False, False],
[False, False, True, True, False],
[False, True, True, False, False]])
这篇关于从数组中屏蔽特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!