Without converting Numpy array to sets, what is the approach to find the union of two Numpy arrays or lists?

+1 vote

Best answer

You can use the union1d() function of Numpy that returns the unique, sorted array of values that are in either of the two 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.union1d(a,b)

array([11, 12, 13, 14, 15, 16, 17, 18])

If you want to find the set union of more than 2 arrays, you need to use the *union1d()* function recursively or the *reduce() *function of* **functools*. Here is an example:

>>> c=np.array([17,18,19,21,20])

>>> np.union1d(np.union1d(a,b),c)

array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21])

>>> from functools import reduce

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

array([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21])