1

How can check for each row in a numpy array if it can be found in another array? So if I have

import numpy as np
a = np.array([[1, 2.6], [3, 4], [2.6, 1]])
b = np.array([[0, 0], [3, 4], [1, 2.6], [4.3, 4], [5, 5]])

I would like to get

array([True, True, False])

Obvioulsly

np.isin(a,b)
array([[ True,  True],
       [ True,  True],
       [ True,  True]])

is not an answer and of course I can write something like

return_ = np.zeros(a.shape[0], dtype=bool)
for index, loc in enumerate(a):
    for loc2 in b:
        if np.allclose(loc, loc2):
            return_[index] = True
            break

but this is slow and looks horrible. I would prefer using proper numpy commands.

1 Answer 1

2

You could try creating a boolean index with appropriate broadcasting and then checking in the result for a True subarray

np.any(np.all(b == a[:, None, :], axis=-1), axis=1)
Sign up to request clarification or add additional context in comments.

1 Comment

Using np.argwhere instead of np.any allows for getting the indices and using np.isclose instead of == deals with floating point issues. Perfect!

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.