Ivan
Ivan

Reputation: 3

Check if numpy arrays is inside another numpy array and create a mask

Given the numpy array a

a = [[[0 0] [1 0] [2 0]]
     [[0 1] [1 1] [2 1]]
     [[0 2] [1 2] [2 2]]]

And the list b

b = [[1, 0], [2, 0]]

How can I get the mask c

c = [[False True True]
     [False False False]
     [False False False]]

Upvotes: 0

Views: 72

Answers (1)

Dev Khadka
Dev Khadka

Reputation: 5451

you can use numpy broadcast feature to compare each number pair in b with all pairs on b like below

## np.newaxis add a new dimension at that position. missing dimension (i.e 
## dimension with size 1) will repeat to match size of corresponding dimension

a = np.asarray([[[0, 0], [1, 0], [2, 0]],
     [[0, 1], [1, 1], [2, 1]],
     [[0, 2], [1, 2], [2, 2]]])[:,:,np.newaxis,:]

b = np.array([[1, 0], [2, 0]])[np.newaxis,:,:]

(a == b).all(axis=3).any(axis=2)

Result

array([[False,  True,  True],
       [False, False, False],
       [False, False, False]])

Upvotes: 1

Related Questions