【问题标题】:Fast interpolation of a scattered DataFrame分散数据帧的快速插值
【发布时间】:2019-10-27 21:07:44
【问题描述】:

TL;DR:问题:有没有一种快速的方法可以在特定坐标处插入分散的 2D 数据集?

如果是这样的话,有人可以提供一个示例,其中提供了“当前解决方案”中使用的示例数据和变量(因为我自己实现它显然很愚蠢)。


问题:

我需要在特定坐标点内插(如果可能的话还外推)分散数据的 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

【问题讨论】:

  • 您的数据点是否始终位于相同的位置?是这样,三角测量可以预先计算,例如见stackoverflow.com/q/51858194/8069403
  • @xdze2 未插值的矩阵始终相同,但需要进行插值的坐标始终不同(小数位数不同等)。如果我使用该方法,我如何访问特定坐标点的插值数据?
  • 使用您想要的任何插值方案从您的数据帧创建一个表面,一次。然后在感兴趣的位置评估该表面。如果您提前知道所有位置,那么甚至不需要循环 - 利用 numpy 数组。 docs.scipy.org/doc/scipy/reference/generated/… 是拟合样条曲面的示例,但 scipy.interpolate 中有很多。
  • @Jdog 直到循环的特定迭代才知道位置(因为它是一个模拟计算每个时间步长),我不认为我可以提前创建一个表面,因为我不知道我需要的分辨率(因为它是一个模拟并且值不可预测)
  • 以样条曲面为例 - 就需要准确评估位置而言,没有空间“分辨率”的概念。您可以在任意位置评估您的表面,我相信调用类似于.ev(x,y)。如果您的数据框没有改变,我无法预见您为什么会重新计算循环内的插值表面。

标签: python python-3.x interpolation


【解决方案1】:

感谢@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)

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 2020-02-16
    • 2022-01-13
    • 1970-01-01
    • 2013-06-03
    • 2015-07-21
    • 2018-12-12
    • 1970-01-01
    • 2014-08-31
    相关资源
    最近更新 更多