How to do frequency counts for unique values in an array with Python NumPy?

Sometimes, we want to do frequency counts for unique values in an array with Python NumPy.

In this article, we’ll look at how to do frequency counts for unique values in an array with Python NumPy.

How to do frequency counts for unique values in an array with Python NumPy?

To do frequency counts for unique values in an array with Python NumPy, we can use the unique method.

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)

print(np.asarray((unique, counts)).T)

to create an array with np.array.

Then we call np.unique on array x and set return_counts to True to return the count of each item in the x array.

Finally, we call np.asarray with unique and counts in an tuple and get the T property to get the items and their counts in a nested list.

Therefore, we see:

[[ 1  5]
 [ 2  3]
 [ 5  1]
 [25  1]]

printed.

Conclusion

To do frequency counts for unique values in an array with Python NumPy, we can use the unique method.