Sometimes, we want to calculate frequency counts for unique values in an array with Python NumPy.
In this article, we’ll look at how to calculate frequency counts for unique values in an array with Python NumPy.
How to calculate frequency counts for unique values in an array with Python NumPy?
To calculate frequency counts for unique values in an array with Python NumPy, we can use the np.unique
method with the return_counts
argument set to True
.
For instance, we write
import numpy as np
x = np.array([1,1,1,2,2,2,5,25,1,1])
unique, counts = np.unique(x, return_counts=True)
a = np.asarray((unique, counts)).T
to call np.unique
with array x
and return_counts
set to True
.
Then we combine the unique
values and its counts
into a single array with nested arrays that has the unique value with its count inside.
Conclusion
To calculate frequency counts for unique values in an array with Python NumPy, we can use the np.unique
method with the return_counts
argument set to True
.