Home > front end >  Fast check if elements in array are within another array (2D)
Fast check if elements in array are within another array (2D)

Time:10-05

Given a 2D array, check if its elements are within another 2D array. Without looping through the second array (if possible).

a = np.array([[1,0], [2,0], [3,0]])
b = np.array([[1,0], [3,0]])

Check if arrays in a are in b. I tried:

np.isin(a, b)

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

And I want:

array([True, False, True])

Thanks

Tried also something like: np.sum(np.isin(a, b), axis=1) <= 1 but it does not work for all the inputs.

CodePudding user response:

You can use np.all(-1), np.any(-1) like below:

>>> a = np.array([[1,0], [2,0], [3,0]])
>>> b = np.array([[1,0], [3,0]])

>>> (a[:, None] == b).all(-1).any(-1)
array([ True, False,  True])


# for more detail
>>> (a[:,None] == b)
array([[[ True,  True],
        [False,  True]],

       [[False,  True],
        [False,  True]],

       [[False,  True],
        [ True,  True]]])

>>> (a[:, None] == b).all(-1)
array([[ True, False],
       [False, False],
       [False,  True]])

another example:

>>> a = np.array([[1,5], [1,9], [3,9]])
>>> b = np.array([[1,5], [3,9]])
>>> (a[:, None] == b).all(-1).any(-1)
array([ True, False,  True])

CodePudding user response:

You can use a combination of np.any and np.all by expanding the arrays and thus broadcasting them against each other:

result = np.any(
    np.all(
        a[None, :, :] == b[:, None, :],
        axis=-1,
    ),
    axis=0,
)
  • Related