Python在2D网格上插值点值

时间:2017-02-28 09:33:40

标签: python arrays numpy scipy interpolation

我有一个常规的2D 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 个答案:

答案 0 :(得分:8)

  • 您还可以使用griddata:

    points = np.array( (X.flatten(), Y.flatten()) ).T
    values = Z.flatten()
    
    from scipy.interpolate import griddata
    Z0 = griddata( points, values, (X0,Y0) )
    
  • X0和Y0可以是数组甚至是网格。

  • 您也可以使用method =
  • 选择插值
  • 也许你可以找到一种方法来驾驭flatten(),但它应该有效。

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

答案 1 :(得分:2)

答案 2 :(得分:0)

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)