简体   繁体   中英

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

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

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM