Python Pandas - Fill NaN with Linear Interpolation


To fill NaN with Linear Interpolation, use the interpolate() method on the Pandas series. At first, import the required libraries −

import pandas as pd
import numpy as np

Create a Pandas series with some NaN values. We have set the NaN using the numpy np.nan

d = pd.Series([10, 20, np.nan, 40, 50, np.nan, 70, np.nan, 90, 100])

Find linear interpolation −

d.interpolate()

Example

Following is the code −

import pandas as pd
import numpy as np

# pandas series
d = pd.Series([10, 20, np.nan, 40, 50, np.nan, 70, np.nan, 90, 100])

print"Series...\n",d

# interpolate
print"\nLinear Interpolation...\n",d.interpolate()

Output

This will produce the following output −

Series...
0   10.0
1   20.0
2    NaN
3   40.0
4   50.0
5    NaN
6   70.0
7    NaN
8   90.0
9  100.0
dtype: float64

Linear Interpolation...
0   10.0
1   20.0
2   30.0
3   40.0
4   50.0
5   60.0
6   70.0
7   80.0
8   90.0
9  100.0
dtype: float64

Updated on: 20-Sep-2021

492 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements