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']

      

+3


source to share


4 answers


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))

      

+7


source


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'])

.

+7


source


This should do it for python arrays

c=[x for x in a if x not in b]+[x for x in b if x not in a]

      

First, it collects all elements from a that are not in b, and then adds all those elements from b that are not in a. This way you get all the elements that are in or b, but not both.

0


source


import numpy as np

a = np.array(['Brian', 'Steve', 'Andrew', 'Craig'])
b = np.array(['Andrew','Steve'])

      

you can use

set(a) - set(b)

      

Output:

set(['Brian', 'Craig'])

      

Note: set operation returns unique values

-1


source







All Articles