I need to count the number of elements greater than a certain value

To count the number of elements greater than a certain value, you need to iterate through each element in the array and compare it against the certain value. If the element is greater than the certain value, you can increment the count by one. Once you have iterated through all the elements, you will have the total count of the number of elements greater than the certain value.


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:

x