itjcms18
itjcms18

Reputation: 4353

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:

['Brian','Craig']

The opposite of what I want is done with this:

c=np.intersect1d(a,b)

which returns

['Andrew' 'Steve']

Upvotes: 15

Views: 21504

Answers (5)

Om Fuke
Om Fuke

Reputation: 662

np.setdiff1d(a,b)

This will return non intersecting value of first argument with second argument
Example:

a = [1,2,3]
b = [1,3]
np.setdiff1d(a,b)  -> returns [2]
np.setdiff1d(b,a)  -> returns []

Upvotes: 4

Robby Cornelissen
Robby Cornelissen

Reputation: 97381

You can use setxor1d. According to the documentation:

Find the set exclusive-or of two arrays.
Return the sorted, unique values that are in only one (not both) of the input arrays.

Usage is as follows:

import numpy

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

c = numpy.setxor1d(a, b)

Executing this will result in c having a value of array(['Brian', 'Craig']).

Upvotes: 23

supinf
supinf

Reputation: 302

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]

It first collects all the 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 elements that are in a or b, but not in both.

Upvotes: 0

NPE
NPE

Reputation: 500923

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

Upvotes: 14

learner
learner

Reputation: 160

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

Upvotes: -2

Related Questions