如何为 Python 中的每个 x 数组值插入具有唯一 y 数组的二维数据?

How do you interpolate 2D data with unique y-arrays for each x-array value in Python?

我正在努力为我拥有的一些二维数据生成插值函数。我的数据不是标准的,因为 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),它将 return 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 不是我应该使用的功能,但我不确定从这里去哪里。

问题是 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

您可以将此代码概括为其他插值选项/更密集的网格等。