By default, np.unique() flattens the input, removes duplicates, and returns the remaining distinct values in sorted order. Setting return_counts=True additionally returns how many times each unique value appeared in the original array, and setting return_index=True returns the index of the first occurrence of each unique value, which together make it a convenient one-call replacement for manually building a frequency table with a Python loop, at C-level speed.
1Understanding np.unique()
By default, np.unique() flattens the input, removes duplicates, and returns the remaining distinct values in sorted order. Setting return_counts=True additionally returns how many times each unique value appeared in the original array, and setting return_index=True returns the index of the first occurrence of each unique value, which together make it a convenient one-call replacement for manually building a frequency table with a Python loop, at C-level speed.
Pass return_counts=True to get element frequencies directly, instead of writing a manual loop or dictionary to count occurrences — it's both faster and returns aligned arrays, unique values and their corresponding counts, ready for further NumPy processing.
import numpy as np
arr = np.array([3, 1, 2, 3, 1, 1])
print(np.unique(arr))2Practical Example
Here is a real-world application of np.unique() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([3, 1, 2, 3, 1, 1])
values, counts = np.unique(arr, return_counts=True)
print(values)
print(counts)3Best Practices
Follow these guidelines when working with np.unique():
1. Use return_counts=True for building frequency tables of array values instead of a manual counting loop
2. Remember np.unique() always returns results in sorted order, not the order values first appeared, which matters if original ordering is meaningful
3. Use np.unique() on flattened multi-dimensional data intentionally, since it collapses shape information by default — reshape the result afterward if the original structure needs to be preserved
Tip: Pass return_counts=True to get element frequencies directly, instead of writing a manual loop or dictionary to count occurrences — it's both faster and returns aligned arrays, unique values and their corresponding counts, ready for further NumPy processing.
import numpy as np
arr = np.array([3, 1, 2, 3, 1, 1])
print(np.unique(arr))