Linear interpolation using numpy.interp

I have a 1-dimensional array A of floats, which is mostly good, but some of the values ​​are missing. Missing data is replaced by nan (not number). I have to replace the missing values ​​in the array with linear interpolation from close good values. So for example:

F7(np.array([10.,20.,nan,40.,50.,nan,30.])) 

must return

 np.array([10.,20.,30.,40.,50.,40.,30.]). 

What is the best thing to do with Python?

Any help would be greatly appreciated

thanks

+7
source share
2 answers

You can use scipy.interpolate.interp1d :

 >>> from scipy.interpolate import interp1d >>> import numpy as np >>> x = np.array([10., 20., np.nan, 40., 50., np.nan, 30.]) >>> not_nan = np.logical_not(np.isnan(x)) >>> indices = np.arange(len(x)) >>> interp = interp1d(indices[not_nan], x[not_nan]) >>> interp(indices) array([ 10., 20., 30., 40., 50., 40., 30.]) 

EDIT : It took me a while to figure out how np.interp works, but it can do this too:

 >>> np.interp(indices, indices[not_nan], x[not_nan]) array([ 10., 20., 30., 40., 50., 40., 30.]) 
+11
source

I would go with pandas . Minimalistic approach with oneliner:

 from pandas import * a=np.array([10.,20.,nan,40.,50.,nan,30.]) Series(a).interpolate() Out[219]: 0 10 1 20 2 30 3 40 4 50 5 40 6 30 

Or if you want to save it as an array:

 Series(a).interpolate().values Out[221]: array([ 10., 20., 30., 40., 50., 40., 30.]) 
+6
source

All Articles