How to Use np.unique in NumPy for Unique Elements
Use
np.unique to find the unique elements of a NumPy array. It returns the sorted unique values and can also return the indices or counts of these unique elements.Syntax
The basic syntax of np.unique is:
np.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
Where:
ar: Input array to find unique elements from.return_index: If True, returns the indices of the input array that give the unique values.return_inverse: If True, returns the indices to reconstruct the original array from the unique array.return_counts: If True, returns the count of each unique element.axis: If specified, finds unique rows or columns along this axis.
python
np.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
Example
This example shows how to find unique elements in a 1D array and get their counts.
python
import numpy as np arr = np.array([2, 3, 2, 5, 3, 7, 5, 7, 7]) unique_values, counts = np.unique(arr, return_counts=True) print("Unique values:", unique_values) print("Counts:", counts)
Output
Unique values: [2 3 5 7]
Counts: [2 2 2 3]
Common Pitfalls
Common mistakes when using np.unique include:
- Not setting
return_counts=Truewhen counts are needed. - Forgetting that the output is sorted, which may affect order-sensitive tasks.
- Using
np.uniqueon multi-dimensional arrays without specifyingaxis, which flattens the array by default.
python
import numpy as np arr = np.array([[1, 2], [1, 2]]) # Wrong: unique without axis flattens the array unique_wrong = np.unique(arr) print("Unique without axis:", unique_wrong) # Right: unique with axis=0 finds unique rows unique_right = np.unique(arr, axis=0) print("Unique rows with axis=0:", unique_right)
Output
Unique without axis: [1 2]
Unique rows with axis=0: [[1 2]]
Quick Reference
| Parameter | Description |
|---|---|
| ar | Input array to find unique elements |
| return_index | Return indices of unique elements in original array (default False) |
| return_inverse | Return indices to reconstruct original array from unique array (default False) |
| return_counts | Return counts of each unique element (default False) |
| axis | Axis to find unique elements along (default None, flattens array) |
Key Takeaways
Use np.unique to get sorted unique elements from a NumPy array.
Set return_counts=True to get how many times each unique element appears.
Specify axis to find unique rows or columns in multi-dimensional arrays.
Remember np.unique returns sorted results, which may reorder elements.
Use return_index or return_inverse to map between original and unique arrays.