Find disjoint values of two arrays
If I have two numpy arrays and want to find non-overlapping values, how do I do that?
Here is a quick example of what I cannot understand.
a = ['Brian', 'Steve', 'Andrew', 'Craig']
b = ['Andrew','Steve']
I want to find non-overlapping values. In this case, I want my output to be:
['Brian','Craig']
The opposite of what I want is done with this:
c=np.intersect1d(a,b)
which returns
['Andrew' 'Steve']
source to share
Considering that none of the objects mentioned in your question are a Numpy array, you don't need Numpy to do this:
c = list(set(a).symmetric_difference(b))
If you want a Numpy array as output, it's trivial to create one:
c = np.array(set(a).symmetric_difference(b))
(This assumes that the order in which the elements appear in c
is irrelevant. If so, you need to specify what the expected order is.)
PS There is also a clean Numpy solution, but I personally find it hard to read:
c = np.setdiff1d(np.union1d(a, b), np.intersect1d(a, b))
source to share
You can use setxor1d
. According to the documentation :
Find a set of exclusive or two arrays.
Return sorted unique values that are in one (not both) input arrays.
Usage looks like this:
import numpy
a = ['Brian', 'Steve', 'Andrew', 'Craig']
b = ['Andrew','Steve']
c = numpy.setxor1d(a, b)
Doing so will lead to what c
matters array(['Brian', 'Craig'])
.
source to share