You can use the following basic syntax to count the number of elements greater than a specific value in a NumPy array:
import numpy as np vals_greater_10 = (data > 10).sum()
This particular example will return the number of elements greater than 10 in the NumPy array called data.
The following example shows how to use this syntax in practice.
Example: Count Number of Elements Greater Than Value in NumPy Array
Suppose we have the following 2D NumPy array with 15 total elements:
import numpy as np #create 2D NumPy array with 3 columns and 5 rows data = np.matrix(np.arange(15).reshape((5, 3))) #view NumPy array print(data) [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] [12 13 14]]
We can use the following syntax to count the total number of elements in the array with a value greater than 10:
#count number of values greater than 10 in NumPy matrix vals_greater_10 = (data > 10).sum() #view results print(vals_greater_10) 4
From the output we can see that 4 values in the NumPy array are greater than 10.
If we manually look at the NumPy array we can confirm that four elements – 11, 12, 13, 14 – are indeed greater than 10.
To find the number of elements less than 10, we can use the less than ( < ) operator instead:
#count number of values less than 10 in NumPy matrix vals_less_10 = (data < 10).sum() #view results print(vals_less_10) 10
From the output we can see that 10 values in the NumPy array are less than 10.
The following tutorials explain how to perform other common operations in Python:
How to Count Number of Elements Equal to NaN in NumPy
How to Count Number of Elements Equal to Zero in NumPy
How to Count Number of Elements Equal to True in NumPy