3

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.

1
  • To clarify, do you want to the Numpy equivalent of [x in b for x in a]? Commented Oct 4, 2021 at 11:52

2 Answers 2

3

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])
Sign up to request clarification or add additional context in comments.

1 Comment

@a_guest edited answer
1

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,
)

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.