1

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?

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

The dtype=bool is not needed, at least for current versions of numpy, as the type is determined automatically from the content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.