Linear Interpolation using numpy.interp

user1789657 picture user1789657 · Oct 31, 2012 · Viewed 24.4k times · Source

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

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

should return

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

What's the best of way of doing this using Python?

Any help would be much appreciated

Thanks

Answer

Fred Foo picture Fred Foo · Oct 31, 2012

You could 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 that can do the job as well:

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