unique() (NumPy)
np.unique() returns the sorted, distinct values of an array with duplicates removed. With return_counts=True it also tells you how many times each distinct value appears.
NumPy
unique is the fast way to find the set of values present in data: the categories in a label array, the distinct IDs in a column. It returns them sorted, which is often more useful than insertion order. The result is always a flat 1-D array even for multi-dimensional input.
Several keyword flags add information in one call: return_counts gives the frequency of each value (a quick histogram of categories), return_index gives the first position of each unique value in the original, and return_inverse gives indices that rebuild the original from the unique values.
For comparing two arrays as sets — intersection, union, difference — the set routines np.intersect1d, np.union1d, and np.setdiff1d build on the same idea.
Syntax
np.unique(a, return_counts=False, return_index=False)Examples
Python
import numpy as np
vals, counts = np.unique(np.array([1, 1, 2, 3, 3, 3]), return_counts=True)
print(vals, counts)Output:
[1 2 3] [2 1 3]