Breaking News
Home / Data Science / NumPy Set Operations # NumPy Set Operations

11 – Set Operations

### Numpy Set Operations¶

In :
import numpy as np


### select the unique elements from an array¶

In :
arr = np.array([1,1,2,2,3,3,4,5,6])
print(np.unique(arr))

[1 2 3 4 5 6]

In :
# return the number of times each unique item appears
arr = np.array([1,1,2,2,3,3,4,5,6])
uniques, counts = np.unique(arr, return_counts=True)
print(uniques)
print(counts)

[1 2 3 4 5 6]
[2 2 2 1 1 1]


### compute the intersection & union of two arrays¶

In :
arr1 = np.array([1,2,3,4,5])
arr2 = np.array([3,4,5,6,7])

In :
# intersection
print(np.intersect1d(arr1, arr2))

[3 4 5]

In :
# union
print(np.union1d(arr1, arr2))

[1 2 3 4 5 6 7]


### compute whether each element of an array is contained in another¶

In :
print(np.in1d(arr1, arr2))

[False False  True  True  True]

In :
# preserve the shape of the array in the output, if the array is of higher dimensions
print(np.isin(arr1, arr2))

[False False  True  True  True]


### compute the elements in an array that are not in another¶

In :
print(np.setdiff1d(arr1, arr2))

[1 2]


### compute the elements in either of two arrays, but not both¶

In :
print(np.setxor1d(arr1, arr2))

[1 2 6 7] 