首页 > 解决方案 > 使用循环对多个数据集进行线性一维插值

问题描述

我有兴趣使用 scipy.interpolate 库执行线性插值。数据集看起来有点像这样: DATAFRAME 用于 X、Y 之间的插值,用于不同的 RUN

我想使用这个插值函数从这个数据集中找到丢失的 Y: DATAFRAME 来使用插值函数

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

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

标签: pandaspython-2.7scipylinear-interpolation

解决方案


据我了解,您需要为每次运行定义一个单独的插值函数。然后,您想将这些函数应用于第二个数据帧。我用 columns 定义了一个数据框df,用 columns定义['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,如下所示: 插值结果


推荐阅读