Greg
Greg

Reputation: 251

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

Upvotes: 10

Views: 19015

Answers (3)

Paul Mamchy
Paul Mamchy

Reputation: 21

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)

Upvotes: 2

N.G
N.G

Reputation: 367

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

Upvotes: 17

Related Questions