Numpy: compare two arrays and create a mask

Viewed 400

I have to np.arrays, say [1, 2, 3, 4] and [1, 2]. I want to create a mask for the first one, such that for every element in the first array, if it is also in the second array, then the value is 1, else 0. Sample outputs:

a = [1, 2, 3, 4]
b = [1, 2]
m = [1, 1, 0, 0]

a = [56, 57, 58, 59]
b = [56, 58]
m = [1, 0, 1, 0]

a = [21, 22, 23]
b = [21, 22, 23]
m = [1, 1, 1]

a = [10, 11, 12]
b = []
m = [0, 0, 0]
1 Answers

Numpy has a built in function to do exactly this : np.isin

example:

>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> y = np.array([1,2])
>>> np.isin(x,y)
array([ True,  True, False, False])

if for whatever reason you had lists and wanted to avoid any non-standard packages, you could use a list comprehension as well (works with the arrays as well..)

>>> [True if xx in y else False for xx in x]
[True, True, False, False]
Related