Numpy Set Operations¶
In [1]:
import numpy as np
select the unique elements from an array¶
In [2]:
arr = np.array([1,1,2,2,3,3,4,5,6])
print(np.unique(arr))
In [3]:
# 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)
compute the intersection & union of two arrays¶
In [4]:
arr1 = np.array([1,2,3,4,5])
arr2 = np.array([3,4,5,6,7])
In [5]:
# intersection
print(np.intersect1d(arr1, arr2))
In [6]:
# union
print(np.union1d(arr1, arr2))
compute whether each element of an array is contained in another¶
In [7]:
print(np.in1d(arr1, arr2))
In [8]:
# preserve the shape of the array in the output, if the array is of higher dimensions
print(np.isin(arr1, arr2))
compute the elements in an array that are not in another¶
In [9]:
print(np.setdiff1d(arr1, arr2))
compute the elements in either of two arrays, but not both¶
In [10]:
print(np.setxor1d(arr1, arr2))