python - 分散数据帧的快速插值
问题描述
TL;DR:问题:有没有一种快速的方法可以在特定坐标处插入分散的二维数据集?
如果是这样,有人可以提供一个示例,其中提供了“当前解决方案”中使用的示例数据和变量(因为我自己实现它显然很愚蠢)。
问题:
我需要在特定坐标点内插(如果可能的话还外推)一个分散数据的 DataFrame(大小 = (34, 18))。DataFrame 始终保持不变。
插值需要快速,因为它在一个循环中完成超过 10.000 次。
将被插值的坐标是事先不知道的,因为它们在每个循环中都会改变。
当前解决方案:
def Interpolation(a, b):
#import external modules
import pandas as pd
from scipy import interpolate
#reading .xlsx file into DataFrame
file = pd.ExcelFile(file_path)
mr_df = file.parse('Model_References')
matrix = mr_df.set_index(mr_df.columns[0])
#interpolation at specific coordinates
matrix = Matrix.stack().reset_index().values
value = interpolate.griddata(matrix[:,0:2], matrix[:,2], (a, b), method='cubic')
return(value)
这种方法不能长时间使用,因为只有下面的两行代码#interpolation at specific coordinates
占了执行时间的 95% 以上。
我的想法:
- 如果需要对数据进行插值和外推,scipy.interpolate.Rbf 似乎是最好的解决方案,但据我所知,它只会创建现有数据的更精细网格,并且不能在特定坐标处输出插值
- 在特定坐标 (a,b) 周围创建一个较小的 4x4 矩阵可能会减少每个循环的执行时间,但我确实很难使用
griddata
较小的矩阵。我创建了一个 5x5 矩阵,第一行和第一列是索引,其他 4x4 条目是中间有特定坐标的数据。但是我得到了一个TypeError: list indices must be integers or slices, not tuple
我不明白的,因为我没有改变任何其他东西。
样本数据:
0.0 0.1 0.2 0.3
0.0 -407 -351 -294 -235
0.0001 -333 -285 -236 -185
0.0002 -293 -251 -206 -161
0.00021 -280 -239 -196 -151
解决方案
感谢@Jdog的评论,我能够弄清楚:
在循环之前创建样条曲线scipy.interpolate.RectBivariateSpline
并读取特定坐标scipy.interpolate.RectBivariateSpline.ev
将插值的执行时间从 255 秒减少到 289 毫秒。
def Interpolation(mesh, a, b):
#interpolation at specific coordinates
value = mesh.ev(stroke, current)
return(value)
#%%
#import external modules
import pandas as pd
from scipy import interp
#reading .xlsx file into DataFrame
file = pd.ExcelFile(file_path)
mr_df = file.parse('Model_References')
matrix = mr_df.set_index(mr_df.columns[0])
mesh = interp.RectBivariateSpline(a_index, b_index, matrix)
for iterations in loop:
value = Interpolation(mesh, a, b)
推荐阅读
- php - 将计费公司分配给订单号 WooCommerce
- javascript - 在 Express 中编写一个发布请求以创建一个具有给定变量的列表
- c# - ADB2C - 令牌缓存过期时处理“在 AcquiretokenSilent API 中传递了 Null 用户”错误
- java - 从 SNMP4j 陷阱接收器获取目标 IP 地址
- vue.js - Vue:设置活动类 - 获取当前 DOM 元素
- c# - 使用 List<> 的 Convert.ChangeType 上的运行时异常
- c# - 从 SelectedItem DataGrid 中获取单元格或行对象
- .net - 使用 MSBuild 构建少数项目失败
- javascript - 只需要使用一次连接事件类型而不使用 cookie 或会话
- batch-file - 批量垂直拆分csv文件