How to Count Unique Values in NumPy Arrays Easily
Use
numpy.unique() with the return_counts=True argument to count unique values in a NumPy array. This function returns the unique values and their counts as arrays.Syntax
The basic syntax to count unique values in a NumPy array is:
numpy.unique(array, return_counts=True)
Here, array is your input NumPy array. The return_counts=True option tells NumPy to also return how many times each unique value appears.
python
numpy.unique(array, return_counts=True)Example
This example shows how to find unique values and count their occurrences in a NumPy array.
python
import numpy as np arr = np.array([1, 2, 2, 3, 3, 3, 4]) unique_values, counts = np.unique(arr, return_counts=True) print("Unique values:", unique_values) print("Counts:", counts)
Output
Unique values: [1 2 3 4]
Counts: [1 2 3 1]
Common Pitfalls
One common mistake is to use numpy.unique() without return_counts=True, which only returns unique values but not their counts. Another is confusing the order of returned values.
Wrong way:
unique = np.unique(arr) print(unique) # Only unique values, no counts
Right way:
unique, counts = np.unique(arr, return_counts=True) print(unique, counts) # Unique values and their counts
Quick Reference
Summary tips for counting unique values in NumPy:
- Use
np.unique(array, return_counts=True)to get counts. - The function returns two arrays: unique values and counts.
- Works with any NumPy array of numbers or strings.
Key Takeaways
Use np.unique with return_counts=True to count unique values in arrays.
The function returns two arrays: unique values and their counts.
Without return_counts=True, only unique values are returned.
This method works for numeric and string NumPy arrays.
Always unpack the two returned arrays to access counts.