2

I have two arrays:

A = np.array([[3, 1], [4, 1], [1, 4]])
B = np.array([[0, 1, 5], [2, 4, 5], [2, 3, 5]])

Is it possible to use numpy.isin rowwise for 2D arrays? I want to check if A[i,j] is in B[i] and return this result into C[i,j]. At the end I would get the following C:

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

It would be great, if this is also doable with the == operator, then I could use it also with PyTorch.

Edit: I also considered check for identical rows in different numpy arrays. The question is somehow similar, but I am not able to apply its solutions to this slightly different problem.

Christian
  • 163
  • 1
  • 10

2 Answers2

3

Not sure that my code solves your problem perfectly. please run it on more test cases to confirm. but i would do smth like i've done in the following code taking advantage of numpys vector outer operations ability (similar to vector outer product). If it works as intended it should work with pytorch as well.

import numpy as np
A = np.array([[3, 1], [4, 1], [1, 4]])
B = np.array([[0, 1, 5], [2, 4, 5], [2, 3, 5]])

AA = A.reshape(3, 2, 1)
BB = B.reshape(3, 1, 3)
(AA == BB).sum(-1).astype(bool)

output:

array([[False,  True],
       [ True, False],
       [False, False]])
yann ziselman
  • 1,952
  • 5
  • 21
  • 1
    Thanks! I was looking for something like this. In contrast to the answer of Whole Brain, this code works also if `A` and `B` have the same dimension. You can reduce it to one line: `(A[:,:,None] == B[:,None,:).any(-1)` – Christian Jun 07 '21 at 14:57
2

Updated answer

Here is a way to do this :

(A == B[..., None]).any(axis=1).astype(bool)
# > array([[False,  True],
#          [ True, False],
#          [False, False]])

Previous answer

You could also do it inside a list comprehension:

[np.isin(a, b) for a,b in zip(A, B)]
# > [array([False,  True]), array([ True, False]), array([False, False])]
np.array([np.isin(a, b) for a,b in zip(A, B)])
# > array([[False,  True],
#          [ True, False],
#          [False, False]])

But, as @alex said it defeats the purpose of numpy.

Whole Brain
  • 2,097
  • 2
  • 8
  • 18