+2 votes
in Programming Languages by (51.1k points)
Without converting Numpy arrays to sets, what is the approach to find the set intersection of two or more Numpy arrays or lists?

1 Answer

+1 vote
by (157k points)
selected by
Best answer

You can use the intersect1d() function of Numpy that returns the sorted, unique elements that are in both of the input Numpy arrays or lists. Here is an example:

>>> import numpy as np
>>> a=np.array([11,12,13,14,15])
>>> b=np.array([14,15,16,17,18])
>>> np.intersect1d(a,b)
array([14, 15])

If you want to find the set intersection of more than two arrays, you need to use the reduce() function of functools or the intersect1d() function recursively. Here is an example:

>>> from functools import reduce
>>> c=np.array([14,15,17,18,19,21,20])
>>> reduce(np.intersect1d,(a,b,c))
array([14, 15])

>>> np.intersect1d(np.intersect1d(a,b),c)
array([14, 15])