Python Pandas - Fill NaN with Polynomial Interpolation

PythonServer Side ProgrammingProgramming

To fill NaN with Polynomial Interpolation, use the interpolate() method on the Pandas series. With that, set the “method” parameter to “polynomial”.

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, 65, 75, 85, np.nan, 100])

Find polynomial interpolation using the method parameter of the interpolate() method −

d.interpolate(method='polynomial', order=2)

Example

Following is the code −

import pandas as pd
import numpy as np

# pandas series
d = pd.Series([10, 20, np.nan, 65, 75, 85, np.nan, 100])

print"Series...\n",d

# interpolate
print"\nPolynomial Interpolation...\n",d.interpolate(method='polynomial', order=2)

Output

This will produce the following output −

Series...
0   10.0
1   20.0
2    NaN
3   65.0
4   75.0
5   85.0
6    NaN
7  100.0
dtype: float64

Polynomial Interpolation...
0   10.000000
1   20.000000
2   42.854015
3   65.000000
4   75.000000
5   85.000000
6   93.532847
7  100.000000
dtype: float64
raja
Published on 20-Sep-2021 10:54:05
Advertisements