Python插值2D网格点的值

10

我有一个普通的二维X、Y和Z数组,我有一个点X0和Y0,我想知道在我的网格上点(X0,Y0)的Z0值。

我发现scipy有插值模块,但据我所知,它插值1D / 2D数组并返回1D / 2D数组,但没有一种方法只返回一个点的一个值。

例如:

#My grid data
X = [ [X11, X12, X13, ..., X1N], 
      [X21, X22, X23, ..., X2N],
          ....
      [XN1, XN2, XN3, ..., XNN]

Y = [ [Y11, Y12, Y13, ..., Y1N], 
      [Y21, Y22, Y23, ..., Y2N],
          ....
      [YN1, YN2, YN3, ..., YNN] ]

Z = [ [Z11, Z12, Z13, ..., Z1N], 
      [Z21, Z22, Z23, ..., Z2N],
          ....
      [ZN1, ZN2, ZN3, ..., ZNN] ]

#Point at which I want to know the value of the Z
X0, Y0 = ..., ...

#Now I want to call any function that'll return the value at point (X0, Y0), Z0 is float value, not array
Z0 = interpolation(X, Y, Z, X0, Y0)

据我所知,类似的功能可以使用scipy.interpolate.interpn实现,但它仅适用于1D数组,当我想处理2D数据时会出现错误。

3个回答

17
  • you can also use griddata :

    points = np.array( (X.flatten(), Y.flatten()) ).T
    values = Z.flatten()
    
    from scipy.interpolate import griddata
    Z0 = griddata( points, values, (X0,Y0) )
    
  • X0 and Y0 can be arrays or even a grid.

  • you can also choose the interpolation with method=
  • perhaps you can find a way to get ride of the flatten(), but it should work.

(https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html)


非常感谢您的回答。我也遇到了同样的问题,现在已经解决了。再次非常感谢。 - Simrandeep Bahal

2

scipy.interpolate griddata在单个点上的表现与数组一样好。将点传递给函数,Voila。您就得到了一个单一的值。

    import numpy as np
    from scipy.interpolate import griddata
    points = np.array([[1,1],[1,2],[2,2],[2,1]])
    values = np.array([1,4,5,2])
    xi=([1.2,1.5])
    result=griddata(points, values, xi,  method='linear')
    print("Value of interpolated function at",xi,"=",*result)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接