How to count the occurrences of a value in a NumPy array in Python

Counting the occurrences of a value in a NumPy array returns the frequency of the value in the array. For example, in [1, 2, 3, 2, 1, 2] , 2 occurs three times.

Solution for How to count the occurrences of a value in a NumPy array in Python : You can use np.count_nonzero() to count the occurrences of a value Call np.count_nonzero(array == value) with array as a NumPy array to count the number of times value appears in array. Despite the name of the function, value can be 0.

Call np.count_nonzero(array == value, axis=n) with n as 1 to count the occurrences of value in each row. Define n as 0 to count the occurrences of value in each column.

print(an_array)


how-to-count-the-occurrences-of-a-value-in-a-numpy-array-in-python