Anyone ever come up to this problem? Let's say you have two arrays like the following
a = array([1,2,3,4,5,6]) b = array([1,4,5])
Is there a way to compare what elements in a exist in b? For example,
c = a == b # Wishful example here print c array([1,4,5]) # Or even better array([True, False, False, True, True, False])
I'm trying to avoid loops as it would take ages with millions of elements. Any ideas?
Cheers
To check if two NumPy arrays A and B are equal: Use a comparison operator (==) to form a comparison array. Check if all the elements in the comparison array are True.
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
pad the smaller array to be as long as the longer array, then substract one from the other and look with np. where((Arr1-Arr2)==0).
Actually, there's an even simpler solution than any of these:
import numpy as np a = array([1,2,3,4,5,6]) b = array([1,4,5]) c = np.in1d(a,b)
The resulting c is then:
array([ True, False, False, True, True, False], dtype=bool)
Use np.intersect1d.
#!/usr/bin/env python import numpy as np a = np.array([1,2,3,4,5,6]) b = np.array([1,4,5]) c=np.intersect1d(a,b) print(c) # [1 4 5]
Note that np.intersect1d gives the wrong answer if a or b have nonunique elements. In that case use np.intersect1d_nu.
There is also np.setdiff1d, setxor1d, setmember1d, and union1d. See Numpy Example List With Doc
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