NumPy: How can I count the number of elements equal to NaN?

NumPy has a function called np.isnan() which can be used to count the number of elements equal to NaN in an array. This function takes an array as an argument and returns an array of boolean values, with True indicating a NaN value and False indicating a non-NaN value. It can then be used in conjunction with np.sum() to count the total number of elements equal to NaN in the array.


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.

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

x