1

I wonder if there is a numpy natural way of creating a binary mask over array1 for elements that are also in array2. Another way to say it, binary mask over array1 for intersection of array1 and 2.

This works:

def bin_mask(a, b):
    return sum(a==n for n in b)

a = np.array([1,2,3,4,5,6,7,8,9,20])
b = np.array([3,5,7])

In: bin_mask(a,b)
Out: array([0, 0, 1, 0, 1, 0, 1, 0, 0, 0])  

But I wonder if there is some numpy prebuilt I am missing.

Edit: Correct answer from comments: np.isin(a, b). I also marked in1d as the correct answer. Both work.

1
  • 2
    np.isin(a, b).view('i1') Commented Feb 13, 2020 at 18:31

1 Answer 1

1

in1d method does the trick too:

>>> np.in1d(a,b)
array([False, False,  True, False,  True, False,  True, False, False, False])
>>> np.in1d(a,b).astype(int)    
array([0, 0, 1, 0, 1, 0, 1, 0, 0, 0])
Sign up to request clarification or add additional context in comments.

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.