22

I have searched high and low and just can't find a way to do it. (It's possible I was searching for the wrong terms.)

I would like to create a mask (eg: [True False False True True]) based on whether each value is in some other list.

a = np.array([11, 12, 13, 14, 15, 16, 17])
mask = a in [14, 16, 8] #(this doesn't work at all!)
#I would like to see [False False False True False True False]

So far the best I can come up with is a list comprehension.

mask = [True if x in other_list else False for x in my_numpy_array]

Please let me know if you know of some secret sauce to do this with NumPy and fast (computationally), as this list in reality is huge.

2 Answers 2

33

Use numpy.in1d():

In [6]: np.in1d(a, [14, 16, 18])
Out[6]: array([False, False, False,  True, False,  True, False], dtype=bool)
Sign up to request clarification or add additional context in comments.

2 Comments

perfect I knew there had to be something :) I'll accept in 12 mins when it lets me ... thanks!
if using dictionary keys or values as the 'other list' make sure to cast them as a list or it doesn't work. i.e., np.in1d(a, list(dict.keys()))
6

Accepted answer is right but currently numpy's docs recommend using isin function instead of in1d

Comments

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.