+2 votes
in Programming Languages by (73.2k points)
Is there any pythonic way to replace all NaN elements with 0s in a pandas Dataframe?

1 Answer

+1 vote
by (346k points)
selected by
 
Best answer

You can use fillna() function to replace NaN elements with 0s.

>>> df = pd.DataFrame([[np.nan, 1, np.nan],[2,3,np.nan],[4,np.nan,5]], columns=list('ABC'), index=list('123'))
>>> df
     A    B    C
1  NaN  1.0  NaN
2  2.0  3.0  NaN
3  4.0  NaN  5.0
>>> df.fillna(0)
     A    B    C
1  0.0  1.0  0.0
2  2.0  3.0  0.0
3  4.0  0.0  5.0

OR

>>> df.fillna(value=0)
     A    B    C
1  0.0  1.0  0.0
2  2.0  3.0  0.0
3  4.0  0.0  5.0

If you want to replace NaN in each column with different values, you can also do that. To replace all NaN elements in column ‘A’, ‘B’, and ‘C’, with 10, 20, and 30 respectively.

>>> values={'A':10,'B':20,'C':30}

>>> df.fillna(value=values)
      A     B     C
1  10.0   1.0  30.0
2   2.0   3.0  30.0

3   4.0  20.0   5.0

To replace only the first NaN element in each column, you need to pass limit=1

>>> df.fillna(value=0, limit=1)

     A    B    C
1  0.0  1.0  0.0
2  2.0  3.0  NaN
3  4.0  0.0  5.0


...