Convert NaN to 0 in Python

Convert NaN to 0 in Python

  • Python
  • 1 min read

This tutorial shows, how to convert the NaN value to 0 in Python.

Convert NaN to 0 Using Numpy Library

You can convert the NaN values to 0 using the Numpy library isnan() function. Below is an example:

from numpy import *

a = array([[1, 2, 3], [0, 3, NaN]])
NaNs = isnan(a)
a[NaNs] = 0
print(a)

Output:

[[1. 2. 3.]
[0. 3. 0.]]

Another example of replacing NaN values with 0 in Python using NumPy library:

from numpy import *

a = 5
b = NaN
print("b = ", b)
if isnan(b) == True : b = 0
print("a = ",a)
print("b = ", b)

Output:

b = nan
a = 5
b = 0

See also: