简体   繁体   中英

Python interpolate point value on 2D grid

I have a regular 2D X, Y and Z array and I have a point X0 and Y0 and I want to know the Z0 value in point (X0, Y0) on my grid.

I found that scipy have interpolate module but as I understand it interpolates 1D/2D arrays and returns 1D/2D array, but there is no method that returns only one value at one point.

For example:

#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)

As I understand the similar function is scipy.interpolate.interpn but it works only with 1D arrays and give out an error when I want to work with 2D data

  • 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 )

scipy.interpolate griddata works on single points just as good as on arrays. Pass the point to the function and Voila. You've got a single value.

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM