np.unique()
np.unique() finds the distinct values in an array, sorted, and can also count them.
In this page:
Syntax
values = np.unique(arr)
values, counts = np.unique(arr, return_counts=True)
np.unique()
np.unique returns the sorted unique elements. With return_counts=True you also get how many times each appears, and return_inverse maps each original element to its unique index. It flattens multi-dimensional input unless you give an axis.
Note:
unique with return_counts is a fast frequency table.
Example: np.unique()
import numpy as np
a = np.array([3, 1, 2, 3, 3, 1])
vals, counts = np.unique(a, return_counts=True)
print(vals)
print(counts)
# Output:
# [1 2 3]
# [2 1 3]
Related Topics
Common Mistakes
- Expecting the original order to be preserved
- Forgetting multi-dimensional input is flattened
- Not asking for counts when needed
Chapter Summary
- unique returns sorted distinct values
- return_counts gives frequencies
- Original order is not kept
- Flattens unless axis is given
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: