user4921177
user4921177

Reputation: 13

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.

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?

Upvotes: 1

Views: 4968

Answers (1)

YXD
YXD

Reputation: 32511

Use 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

Upvotes: 5

Related Questions