Search code examples
pythonscipy

Interpolation given a lookup table of f(x, y) = z, if I have an x and z value, how can I interpolate y?


I have a lookup table that looks as follows. Given an x value and f(x, y) value, is there a scipy interpolation scheme to query the lookup table to find the y value which is best supported by the data?

lookup_table

For example, given this data (which is f(x,y) = 0.1 * x + y), given: x = 1.5, f(x,y) = 2, I should get y = 1.85.

data

Naively I'm thinking I can do 2 separate 1d interpolations -- first on the x axis with the given x (let's call it x*) to generate a 1d array for f(x*. y), then do another 1d interpolation on the given f(x, y) to compute y.


Solution

  • You can accomplish this using scipy.interpolate.griddata. For this to work, you need to create the arrays for all the points and then flatten them when you pass them to the function.

    import numpy as np
    from scipy.interpolate import griddata
    
    x = np.arange(1, 6)
    y = np.arange(1, 6)
    X, Y = np.meshgrid(x, y)
    Z = 0.1*X + Y
    
    res = griddata((X.flatten(), Z.flatten()), Y.flatten(), (1.5, 2))
    print(res)  # 1.85