Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise in-operator between two arrays

I'm wondering if there is a nice and elegant way to do an element-wise in comparison between two arrays.

arr1 = [[1, 2], 
        [3, 4], 
        [5, 6]]

àrr2 = [3,
        5, 
        6]

result = arr2 in arr1

Now I want a result like :

[False, False, True]

Thanks a lot in advance!

Edit: I'm sorry, my example was a bit misleading. I want this to be performed element-wise, meaning I want to check, whether arr2[0] is in arr1[0], arr2[1] is in arr2[1] and so on.. I updated the example

Also the real arrays are much larger, so I would like to do it without loops

like image 438
brigado Avatar asked Jan 01 '23 12:01

brigado


2 Answers

You can use operator.contains:

>>> arr1 = [[1, 2], [4, 5], [7, 8]]
>>> arr2 = [3, 4, 7]
>>> list(map(contains, arr1, arr2)
[False, True, True]

Or for numpy use np.isin

>>> arr1 = np.array([[1, 2], [4, 5], [7, 8]])
>>> arr2 = np.array([3, 4, 7])
>>> np.isin(arr2, arr1).any(1)
[False  True  True]
like image 92
Jab Avatar answered Jan 17 '23 16:01

Jab


IIUC, there is the wonderful np.in1d to do this:

In [16]: np.in1d(arr2, arr1)
Out[16]: array([False,  True,  True])

From the docs, this function does the following:

Test whether each element of a 1-D array is also present in a second array.

like image 42
sacuL Avatar answered Jan 17 '23 15:01

sacuL