【问题标题】:How do you interpolate 2D data with unique y-arrays for each x-array value in Python?如何在 Python 中为每个 x 数组值插入具有唯一 y 数组的 2D 数据?
【发布时间】:2019-11-07 13:44:55
【问题描述】:

我正在努力为我拥有的一些二维数据生成插值函数。我的数据不是标准的,因为 x 数组中的每个值都对应一个唯一的 y 数组。例如:

x = [0.1, 0.2]

y1 = [13.719, 10.488, 9.885, 9.704]       #Corresponding to x=0.1

y2 = [13.34, 10.259,  9.275,  8.724]      #Corresponding to x=0.2

z1 = [1395., 2209., 2411., 2555.]         #Corresponding to y1

z2 = [1570., 2261., 2519., 2682.]         #Corresponding to y2

理想情况下,我想生成一个函数 f(x, y),它将返回 z 的插值。

到目前为止,我唯一的尝试是通过使用:

from scipy.interpolate import interp2d

interpolation = interp2d(x, [y1, y2], [z1, z2])

不出所料,这会导致以下错误消息:

ValueError: x and y must have equal lengths for non rectangular grid

我理解我收到此消息的原因,并理解 interp2d 不是我应该使用的功能,但我不确定从这里去哪里。

【问题讨论】:

    标签: python arrays scipy interpolation


    【解决方案1】:

    问题在于interp2d 处理排列在矩形网格上的数据。您只有 8 个未排列在矩形 xy 网格中的数据点。

    您可以考虑一个矩形 2x8,它包含您的 xy 数据的所有可能组合,但您只有 8 个数据点(z 值)。

    以下是具有更通用scipy.interpolate.griddata 函数的示例解决方案:

    x = [0.1, 0.2]
    y1 = [13.719, 10.488, 9.885, 9.704]       #Corresponding to x=0.1
    y2 = [13.34, 10.259,  9.275,  8.724]      #Corresponding to x=0.2
    z1 = [1395., 2209., 2411., 2555.]         #Corresponding to y1
    z2 = [1570., 2261., 2519., 2682.]         #Corresponding to y2
    
    y=np.concatenate((y1,y2))  # collapse all y-data into a single array
    
    # obtain x- and y- grids
    grid_x, grid_y =np.meshgrid(np.array(x), y)[0].T, np.meshgrid(np.array(x), y)[1].T
    points=np.stack((np.repeat(x,4).T,y))  #obtain xy corrdinates for data points
    values=np.concatenate((z1,z2)) #obtain values 
    grid_z0 = griddata(points.T, values, (grid_x, grid_y), method='nearest') #Nearest neighbour interpolation
    

    您可以将此代码推广到其他插值选项/更密集的网格等。

    【讨论】:

    • 太好了,感谢您的回复。我以前不知道网格数据,这肯定解决了我的问题。对于这个问题的任何未来读者,要实际提取给定 x/y 的新 z 值,请将最后一行调整为:grid_z0 = griddata(points.T, values, (new_x, new_y), method='cubic')。三次是可选的,但“最近”不会在点之间插值。
    • 当然。我只是展示了一个简单的解决方案,应该使用自己的参数(插值类型和网格)
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2022-01-25
    • 2018-01-19
    相关资源
    最近更新 更多