+1 vote
in Programming Languages by (66.8k points)
There are some NaN in an array, and I want to replace them with 0. Is there any Python function for replacing NaN with some value?

1 Answer

+3 votes
by (66.2k points)
selected by
 
Best answer

Numpy function nan_to_num() can be used to replace NaN with any given value. You can supply the given value to the argument 'nan' of this function.

Here is an example to replace NaN with 0 or 100:

>>> import numpy as np

>>> aa = np.array([[np.nan,4,5], [9,10,np.nan]])

>>> aa

array([[nan,  4.,  5.],

       [ 9., 10., nan]])

>>> np.nan_to_num(aa, nan=0)

array([[ 0.,  4.,  5.],

       [ 9., 10.,  0.]])

>>> np.nan_to_num(aa, nan=100)

array([[100.,   4.,   5.],

       [  9.,  10., 100.]])

>>> 


...