How to replace NaN values by Zeroes in a column of a Pandas Series?


To replace NaN values by zeroes or other values in a column of Pandas Series, we can use s.fillna() method.

Steps

  • Create a one-dimensional ndarray with axis labels (including time series).

  • Print the input series.

  • Use s.fillna(0) to replace NaN in the series with value 0.

  • Similarly, use s.fillna(5) and s.fillna(7) to replace NaN in series with values 5 and 7, respectively.

  • Print the replaced NaN series.

Example

 Live Demo

import pandas as pd
import numpy as np

s = pd.Series([1, np.nan, 3, np.nan, 3, np.nan, 7, np.nan, 3])
print "Input series is:
", s print "After replacing NaN with 0:
", s.fillna(0) print "After replacing NaN with 5:
", s.fillna(5) print "After replacing NaN with 7:
", s.fillna(7)

Output

Input series is:
   x    y   z
0 5.0  NaN  NaN
1 NaN  1.0  1.0
2 1.0  NaN  NaN
3 NaN 10.0  NaN
After replacing NaN with 0:
    x    y    z
0 5.0   0.0  0.0
1 0.0   1.0  1.0
2 1.0   0.0  0.0
3 0.0  10.0  0.0
After replacing NaN with 5: 
   x    y   z
0 5.0  5.0  5.0
1 5.0  1.0  1.0
2 1.0  5.0  5.0
3 5.0 10.0  5.0
After replacing NaN with 7:
   x    y   z
0 5.0  7.0  7.0
1 7.0  1.0  1.0
2 1.0  7.0  7.0
3 7.0 10.0  7.0

Updated on: 30-Aug-2021

690 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements