【问题标题】:Linear 1D interpolation on multiple datasets using loops使用循环对多个数据集进行线性一维插值
【发布时间】:2019-07-02 19:08:11
【问题描述】:

我对使用 scipy.interpolate 库执行线性插值很感兴趣。数据集看起来有点像这样: DATAFRAME for interpolation between X, Y for different RUNs

我想使用这个插值函数从这个数据集中找到缺失的 Y: DATAFRAME to use the interpolation function

此处给出的运行次数仅为 3,但我正在运行的数据集将运行 1000 次。因此,如果您能建议如何使用迭代函数进行插值,将不胜感激?

from scipy.interpolate import interp1d
for RUNNumber in range(TotalRuns)
 InterpolatedFunction[RUNNumber]=interp1d(X, Y)

【问题讨论】:

    标签: pandas python-2.7 scipy linear-interpolation


    【解决方案1】:

    据我了解,您需要为每次运行定义一个单独的插值函数。然后,您想将这些函数应用于第二个数据帧。我定义了一个数据框df,列['X', 'Y', 'RUN'],第二个数据框new_df,列['X', 'Y_interpolation', 'RUN']

    interpolating_functions = dict()
    for run_number in range(1, max_runs):
        run_data = df[df['RUN']==run_number][['X', 'Y']]
        interpolating_functions[run_number] = interp1d(run_data['X'], run_data['Y'])
    

    现在我们为每次运行都有插值函数,我们可以使用它们来填充新数据帧中的“Y_interpolation”列。这可以使用apply 函数来完成,该函数接受一个函数并将其应用于数据帧中的每一行。因此,让我们定义一个插值函数,它将获取这个新 df 的一行,并使用 X 值和运行次数来计算插值的 Y 值。

    def interpolate(row):
        int_func = interpolating_functions[row['RUN']]
        interp_y = int_func._call_linear([row['X'])[0] #the _call_linear method
                                                       #expects and returns an array
        return interp_y[0]
    

    现在我们只使用apply 和我们定义的interpolate 函数。

    new_df['Y_interpolation'] = new_df.apply(interpolate,axis=1)
    

    我使用的是 pandas 0.20.3 版,这给了我一个如下所示的 new_df:

    【讨论】:

    • 谢谢@A。 Entuluva 非常了解如何处理这个问题陈述的总体思路。但是,我在尝试使用“应用”功能时收到错误“ValueError:错误的项目数传递 2,位置意味着 1”。你能分享你的代码吗?我正在使用这个: new_df1={'X': [1,4,12,998,1,4,12,998,1,4,12,998], 'RUN':[1,1,1,1,2,2, 2,2,3,3,3,3] } new_df=pd.DataFrame(new_df1) new_df['Y_interpolation']=new_df.apply(interpolate,axis=1)
    • 您的代码对我来说运行良好。你用的是什么版本的熊猫? apply 的语法可能已更改。
    • 嗨@A.Entuluva,我使用的是0.16.2。升级到 0.20.3 后我会尝试同样的方法。谢谢。
    猜你喜欢
    • 2020-03-19
    • 2023-03-08
    • 2019-05-18
    • 2015-06-01
    • 2013-11-06
    • 2021-12-13
    • 2013-09-28
    • 1970-01-01
    • 2020-10-19
    相关资源
    最近更新 更多