itjcms18 itjcms18 - 10 months ago 90
Python Question

Find the non-intersecting values of two arrays

If I have two numpy arrays and want to find the the non-intersecting values, how do I do it?

Here's a short example of what I can't figure out.

a = ['Brian', 'Steve', 'Andrew', 'Craig']
b = ['Andrew','Steve']

I want to find the non-intersecting values. In this case I want my output to be:


The opposite of what I want is done with this:


which returns

['Andrew' 'Steve']

Answer Source

Given that none of the objects shown in your question are Numpy arrays, you don't need Numpy to achieve this:

c = list(set(a).symmetric_difference(b))

If you have to have a Numpy array as the output, it's trivial to create one:

c = np.array(set(a).symmetric_difference(b))

(This assumes that the order in which elements appear in c does not matter. If it does, you need to state what the expected order is.)

P.S. There is also a pure Numpy solution, but personally I find it hard to read:

c = np.setdiff1d(np.union1d(a, b), np.intersect1d(a, b))