[英]Python: create mask from two arrays
I would like to create a mask from defined entries of one array and apply it to other arrays. 我想根据一个数组的定义条目创建一个掩码,并将其应用于其他数组。 I'm a beginner in Python and didn't know how to search for it. 我是Python的初学者,不知道如何搜索。
Example: 例:
values = [ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]
wanted = [ 1., 4., 7., 10.]
mask = [True, False, False, True, False, False, True, False, False, True]
other_array_1 = [ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
other_array_2 = [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
wanted_array_1 = other_array_1[mask]
wanted_array_1 = [1, 7, 13, 19]
wanted_array_2 = other_array_2[mask]
wanted_array_2 = [0, 6, 12, 18]
I've found how I select the wanted values: 我发现了如何选择所需的值:
select = [i for i in wanted if i in values]
then I've tried to make a mask out of that: 然后我试图用它做一个面具:
mask_try = (i for i in wanted if i in values)
I'm not sure what I created, but it's not a mask. 我不确定我创建了什么,但这不是蒙版。 It tells me it's a 告诉我这是一个
<generator object <genexpr> at 0x7f6aa4872460>
Anyway, is there a way to create a mask like this for numpy arrays? 无论如何,有没有办法为numpy数组创建这样的掩码?
Use in1d
在in1d
使用
>>> values = [ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]
>>> wanted = [ 1., 4., 7., 10.]
>>> mask = np.in1d(values, wanted)
>>> mask
array([ True, False, False, True, False, False, True, False, False, True], dtype=bool)
>>>
The usual caveats about floating point equality apply. 有关浮点数相等的常见警告适用。 If your inputs are sorted you can also take a look at np.searchsorted
如果您输入的内容已排序,则还可以查看np.searchsorted
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.