【问题标题】:pandas extrapolation of polynomial多项式的熊猫外推
【发布时间】:2015-09-17 15:13:00
【问题描述】:

使用df.interpolate() 在 pandas 中很容易进行插值 pandas 中是否有一种方法可以以同样优雅的方式进行推断。我知道我的外推适合二次多项式。

【问题讨论】:

  • 您可能必须使用scipy.interpolate.UnivariateSpline,它有一个ext 选项。
  • Related: Extrapolate values in Pandas DataFrame,不过是一个更简单的情况,可以通过其他方法解决。
  • 该问题现在有一个answer,其中包含多项式外推的详细信息。

标签: python numpy pandas


【解决方案1】:

“以同样的优雅”是一个有点高的要求,但这是可以做到的。据我所知,您需要手动计算外推值。请注意,除非您操作的数据实际上遵守插值形式的定律,否则这些值不太可能非常有意义。

例如,由于您要求进行二次多项式拟合:

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

现在 p(t) 是时间 t 的最佳拟合多项式的值。

【讨论】:

    【解决方案2】:

    外推

    请参阅此answer,了解如何将DataFrame3rd order polynomial 的每一列的值extrapolate。通过更改func(),可以轻松使用different order (e.g. 2nd order) polynomial

    来自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])
    

    【讨论】:

      猜你喜欢
      • 2015-01-10
      • 2017-09-11
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 2015-08-12
      • 2021-02-10
      相关资源
      最近更新 更多