NumPy: How to Count Number of Elements Equal to True


You can use the following basic syntax to count the number of elements equal to True in a NumPy array:

import numpy as np

np.count_nonzero(my_array)

This particular example will return the number of elements equal to True in the NumPy array called my_array.

The following example shows how to use this syntax in practice.

Example: Count Number of Elements Equal to True in NumPy Array

The following code shows how to use the count_nonzero() function to count the number of elements in a NumPy array equal to True:

import numpy as np

#create NumPy array
my_array = np.array([True, False, False, False, True, True, False, True, True])

#count number of values in array equal to True
np.count_nonzero(my_array)

5

From the output we can see that 5 values in the NumPy array are equal to True.

We can manually look at the NumPy array to verify that there are indeed three elements equal to True in the array.

If you would instead like to count the number of element equal to False, you can subtract the results from the count_nonzero() function from the size() function as follows:

import numpy as np

#create NumPy array
my_array = np.array([True, False, False, False, True, True, False, True, True])

#count number of values in array equal to False
np.size(my_array) - np.count_nonzero(my_array)

4

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

Note: If you have any NaN values in your NumPy array, the count_nonzero() function will count each NaN value as an element equal to True.

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

Leave a Reply

Your email address will not be published. Required fields are marked *