Pandas polynomial extrapolation

Interpolation is easy in pandas using df.interpolate() is there a method in pandas that with the same elegance does something like extrapolation. I know that my extrapolation is adapted to a polynomial of the second degree.

+6
source share
2 answers

“With the same elegance” is a somewhat high order, but it can be done. As far as I know, you will need to calculate the extrapolated values ​​manually. Please note that it is very unlikely that these values ​​will be very significant, unless the data you are using actually obeys the law of the shape of the interpolator.

For example, since you requested a polynomial polygon of the second degree:

 import numpy as np t = df["time"] dat = df["data"] p = np.poly1d(np.polyfit(t,data,2)) 

Now p (t) is the value of the polynomial of best correspondence at time t.

+1
source

Extrapolation

See this answer on how to extrapolate the values ​​of each column of a DataFrame with a 3 rd order polynomial . A different order (e.g. 2 nd order) polynomial can be easily used by changing func() .

Excerpt from the answer

 # Function to curve fit to the data def func(x, a, b, c, d): return a * (x ** 3) + b * (x ** 2) + c * x + d # Initial parameter guess, just to kick off the optimization guess = (0.5, 0.5, 0.5, 0.5) # Create copy of data to remove NaNs for curve fitting fit_df = df.dropna() # Place to store function parameters for each column col_params = {} # Curve fit each column for col in fit_df.columns: # Get x & y x = fit_df.index.astype(float).values y = fit_df[col].values # Curve fit column and get curve parameters params = curve_fit(func, x, y, guess) # Store optimized parameters col_params[col] = params[0] # Extrapolate each column for col in df.columns: # Get the index values for NaNs in the column x = df[pd.isnull(df[col])].index.astype(float).values # Extrapolate those points with the fitted function df[col][x] = func(x, *col_params[col]) 
0
source

All Articles