Counting occurrences in numpy array

suggest change

To count the occurrences of a value in a NumPy array, compare the array with that value and count the True results:

>>> import numpy as np
>>> values = np.array([0, 3, 4, 3, 5, 4, 7])
>>> print(np.count_nonzero(values == 3))
2

The comparison produces a boolean array, and count_nonzero counts the True entries. This works for arrays of any shape or dtype.

There are two methods I use to count occurrences of all unique values in NumPy: unique and bincount. unique automatically flattens multidimensional arrays, while bincount only works with 1-dimensional arrays of non-negative integers.

>>> unique, counts = np.unique(values, return_counts=True)
>>> print(unique, counts)  # counts[i] is the frequency of unique[i]
[0 3 4 5 7] [1 2 2 1 1]
>>> bin_count = np.bincount(values)
>>> print(bin_count)  # bin_count[i] is the frequency of i
[1 0 0 2 2 1 0 1]

If your data are NumPy arrays, it is generally much faster to use NumPy methods than to convert your data to generic methods.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents