DHEERAJ KULKARNI
DHEERAJ KULKARNI

Reputation: 25

How to interpolate list containing arrays?

I would like to interpolate between two lists in which 1st one contains numbers and second one contains arrays.

I tried using interp1d from scipy, but it did not work

    from scipy import interpolate

    r = [2,3,4]
    t = [5,6,7]
    f = [r,t]
    q = [10,20]
    c = interpolate.interp1d(q, f)

I would like to get an array, for example at value 15, which should be interpolated values between r and t arrays

Error message:

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

Upvotes: 0

Views: 944

Answers (2)

mikuszefski
mikuszefski

Reputation: 4043

In the simple example of the OP it does not make a difference whether one takes 1D or 2D interpolation. If more vectors come into play, however, it makes a difference. Here both options, using numpy and taking care of floating point.

from scipy.interpolate import interp1d
from scipy.interpolate import interp2d
import numpy as np
r = np.array( [ 1, 1, 2], np.float )
s = np.array( [ 2, 3, 4], np.float )
t = np.array( [ 5, 6, 12], np.float ) # length of r,s,t,etc must be equal
f = np.array( [ r, s, t ] )
q = np.array( [ 0, 10, 20 ], np.float )  # length of q is length of f


def interpolate_my_array1D( x, xData, myArray ):
    out = myArray[0].copy()
    n = len( out )
    for i in range(n):
        vec = myArray[ : , i ]
        func = interp1d( xData, vec )
        out[ i ] = func( x )
    return out


def interpolate_my_array2D( x, xData, myArray ):
    out = myArray[0].copy()
    n = len( out )
    xDataLoc = np.concatenate( [ [xx] * n for xx in xData ] )
    yDataLoc = np.array( range( n ) * len( xData ), np.float )
    zDataLoc = np.concatenate( myArray )
    func = interp2d( xDataLoc, yDataLoc, zDataLoc )
    out = np.fromiter( ( func( x, yy ) for yy in range(n) ), np.float )
    return out

print interpolate_my_array1D( 15., q, f )
print interpolate_my_array2D( 15., q, f )

giving

>> [3.5 4.5 5.5]
>> [2.85135135 4.17567568 6.05405405]

Upvotes: 1

Yayati Sule
Yayati Sule

Reputation: 1631

Following is the link to the interp1d function in scipy documentation interpolate SciPy. From the docs you can see that the function does not take a list of list as an input. the inputs need to be either numpy arrays or list of primitive values.

Upvotes: 0

Related Questions