'Is there an equivalent numpy function to isin() that works row based?
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.
Solution 1:[1]
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
allvalues True on the last dimension? (i.e,[0,1]==[0,1]needs to be[True, True]) - is
anyof those aggregates True? (one of[0,1]==[0,1](True) or[0,1]!=[0,2](False) is sufficient)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
