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
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With