pandas - 使用循环对多个数据集进行线性一维插值
问题描述
我有兴趣使用 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)
解决方案
据我了解,您需要为每次运行定义一个单独的插值函数。然后,您想将这些函数应用于第二个数据帧。我用 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)
推荐阅读
- c++ - 如何使用 Turbo C++ 并行运行两个功能,一个用于键盘,一个用于鼠标?
- arrays - 输入数组 Angular 7
- node.js - 子文档中的简单查询失败
- kubernetes - 为 Kubernetes 资源实现自定义终结器
- python - 如何从数组中获取特定单词?
- python - 根据元组键(key1,key2)中的第一个键过滤字典,其中key1
- vue.js - VUE:使用多个输入计算二维数组
- javascript - 是否可以在组合框的中心对齐文本?
- python - 如何在另一个文件目录中的另一个脚本中导入 Python 文件?
- datasource - 如何在表单中通过键强制加载和项目?