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.
Additional Resources
The following tutorials explain how to perform other common operations in Python:
How to Calculate the Mode of NumPy Array
How to Map a Function Over a NumPy Array
How to Sort a NumPy Array by Column