Issue
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.
Solution
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])
Answered By - user1740577
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.