convert nan value to zero convert nan value to zero numpy numpy

convert nan value to zero


Where A is your 2D array:

import numpy as npA[np.isnan(A)] = 0

The function isnan produces a bool array indicating where the NaN values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.


This should work:

from numpy import *a = array([[1, 2, 3], [0, 3, NaN]])where_are_NaNs = isnan(a)a[where_are_NaNs] = 0

In the above case where_are_NaNs is:

In [12]: where_are_NaNsOut[12]: array([[False, False, False],       [False, False,  True]], dtype=bool)