How to Count Occurrences of Elements in NumPy

To count the occurrences of elements in a NumPy array, you can use the numpy.count_nonzero() function. This function returns the counts of each element in the array, allowing you to quickly determine the number of occurrences of any element in the array. Additionally, the np.unique() function can be used to identify the unique elements in an array, which can then be used with numpy.count_nonzero() to count their occurrences.


You can use the following methods to count the occurrences of elements in a NumPy array:

Method 1: Count Occurrences of a Specific Value

np.count_nonzero(x == 2)

Method 2: Count Occurrences of Values that Meet One Condition

np.count_nonzero(x < 6)

Method 3: Count Occurrences of Values that Meet One of Several Conditions

np.count_nonzero((x == 2) | (x == 7))

The following examples show how to use each method in practice with the following NumPy array:

import numpy as np

#create NumPy array
x = np.array([2, 2, 2, 4, 5, 5, 5, 7, 8, 8, 10, 12])

Example 1: Count Occurrences of a Specific Value

The following code shows how to count the number of elements in the NumPy array that are equal to the value 2:

#count number of values in array equal to 2
np.count_nonzero(x == 2)

3

From the output we can see that 3 values in the NumPy array are equal to 2.

Example 2: Count Occurrences of Values that Meet One Condition

The following code shows how to count the number of elements in the NumPy array that have a value less than 6:

#count number of values in array that are less than 6
np.count_nonzero(x < 6)

7

From the output we can see that 7 values in the NumPy array have a value less than 6.

Example 3: Count Occurrences of Values that Meet One of Several Conditions

The following code shows how to count the number of elements in the NumPy array that are equal to 2 or 7:

#count number of values in array that are equal to 2 or 7
np.count_nonzero((x == 2) | (x == 7))

4

From the output we can see that 4 values in the NumPy array are equal to 2 or 7.

The following tutorials explain how to perform other common operations in Python:

x