NumPy: How to Count Number of Elements Equal to NaN


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

import numpy as np

np.count_nonzero(np.isnan(my_array))

This particular example will return the number of elements equal to NaN 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 NaN 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 NaN:

import numpy as np

#create NumPy array
my_array = np.array([5, 6, 7, 7, np.nan, 12, 14, 10, np.nan, 11, 14])

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

2

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

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

If you would instead like to count the number of elements not equal to NaN, you can use the count_nonzero() function as follows:

import numpy as np

#create NumPy array
my_array = np.array([5, 6, 7, 7, np.nan, 12, 14, 10, np.nan, 11, 14])

#count number of values in array not equal to NaN
np.count_nonzero(~np.isnan(my_array))

9

From the output we can see that 9 values in the NumPy array are not equal to NaN.

Note: The tilde (~) operator is used to represent the opposite of some expression. In this example, it counts the number of elements not equal to NaN.

Additional Resources

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

How to Calculate the Mode of NumPy Array
How to Count Unique Values in NumPy Array
How to Count Number of Elements Equal to Zero in NumPy
How to Count Number of Elements Equal to True in NumPy

Leave a Reply

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