How to Replace NaN Values with Zero in NumPy


You can use the following basic syntax to replace NaN values with zero in NumPy:

my_array[np.isnan(my_array)] = 0

This syntax works with both matrices and arrays.

The following examples show how to use this syntax in practice.

Example 1: Replace NaN Values with Zero in NumPy Array

The following code shows how to replace all NaN values with zero in a NumPy array:

import numpy as np

#create array of data
my_array = np.array([4, np.nan, 6, np.nan, 10, 11, 14, 19, 22])

#replace nan values with zero in array
my_array[np.isnan(my_array)] = 0

#view updated array
print(my_array)

[ 4.  0.  6.  0. 10. 11. 14. 19. 22.]

Notice that both NaN values in the original array have been replaced with zero.

Example 2: Replace NaN Values with Zero in NumPy Matrix

Suppose we have the following NumPy matrix:

import numpy as np

#create NumPy matrix
my_matrix = np.matrix(np.array([np.nan, 4, 3, np.nan, 8, 12]).reshape((3, 2)))

#view NumPy matrix
print(my_matrix)

[[nan  4.]
 [ 3. nan]
 [ 8. 12.]]

We can use the following code to replace all NaN values with zero in the NumPy matrix:

#replace nan values with zero in matrix
my_matrix[np.isnan(my_matrix)] = 0

#view updated array
print(my_matrix)

[[ 0.  4.]
 [ 3.  0.]
 [ 8. 12.]]

Notice that both NaN values in the original matrix have been replaced with zero.

Related: How to Remove NaN Values from NumPy Array

Additional Resources

The following tutorials explain how to perform other common tasks in NumPy:

How to Fill NumPy Array with Values
How to Remove Specific Elements from NumPy Array
How to Replace Elements in NumPy Array
How to Get Specific Row from NumPy Array

Leave a Reply

Your email address will not be published.