Search code examples
pythonnumpyscipy

Interpolation between elements of two arrays with common X-axis


I have a NumPy array of size (n,2) that I need to linearly interpolate. Example: consider the (3,2) array below.

0.2 0.4
0.3 0.6
0.4 0.8

I want to linearly interpolate between the two columns (column 0 being lower bound values and column 1 being upper bound values) row-by-row. Each row has the same lower x and upper x value (5 and 10 respectively). If I interpolate this for x=7.5 I should get:

0.3
0.45
0.6

Using SciPy:

from scipy.interpolate import interp1d

y = np.array([[.2,.4], [.3, .6], [.4, .8]])
xl = 5
xh = 10
f = interp1d([xl, xh], [y[:,0], y[:,1]])
f(7.5)

Error at f = interp1d(...):

ValueError: x and y arrays must be equal in length along interpolation axis.

Using NumPy:

import numpy as np

y = np.array([[.2,.4], [.3, .6], [.4, .8]])
xl = 5
xh = 10
f = np.interp(7.5, [xl, xh], [y[:,0], y[:,1]])

Error:

ValueError: object too deep for desired array

This needs to be applied to a large matrix. What is the most efficient solution (without using a for loop)?


Solution

  • You almost had it, you just need to pass the transpose of what you're passing for y, which is actually just the y array itself.

    from scipy.interpolate import interp1d
    import numpy as np
    
    y = np.array([[0.2, 0.4], 
                  [0.3, 0.6], 
                  [0.4, 0.8]])
    xl = 5
    xh = 10
    f = interp1d([xl, xh], y)
    print(f(7.5))  # [0.3  0.45 0.6 ]