Home > Back-end >  Is there an equivalent numpy function to isin() that works row based?
Is there an equivalent numpy function to isin() that works row based?

Time:04-02

Say I have two numpy array's, for example:

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

and

arr2 = np.array([[0,1],[1,2]])

What I want now is a function that compares the rows of arr1 with the rows of arr2 and outputs a list of the following shape

[True,False,True,False]

Where the first and second to last place are true since they represent a row in arr1 that also appears in arr2.

I tried using numpy.isin(arr1,arr2) however that gives an array of shape arr1 with the elements of arr1 compared with the elements arr2.

Thanks in advance.

CodePudding user response:

You can use broadcasting:

(arr1==arr2[:,None]).all(2).any(0)

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

explanation:

  • expand arr2 to an extra dimension:arr2[:,None]
  • compare element-wise
  • are all values True on the last dimension? (i.e, [0,1]==[0,1] needs to be [True, True])
  • is any of those aggregates True? (one of [0,1]==[0,1] (True) or [0,1]!=[0,2] (False) is sufficient)
  • Related