python - replace zeros in numpy array with linear interpolation between its preceding and succeeding values -


assuming have array a = np.array([1,2,0,4,0,5,0,0,11]) ,how can get:

array([ 1,  2,  3,  4,  4.5,  5,  7,  9, 11]) 

what have tried is:

from scipy.interpolate import interp1d  = np.array([1,2,0,4,0,5,0,0,11]) b = a[np.nonzero(a)] brange = np.arange(b.shape[0]) interp = interp1d(brange, b) 

this seems actual job of finding in-between values. instance:

print (interp(1), interp(1.5), interp(2), interp(2.5), interp(3)) #out: 2.0 3.0 4.0 4.5 5.0 

but can't figure out how re-construct original array interp. tried solution this question, had exact same problem solution well.

update:

i did quick benchmark both solution using numpy , pandas, here result:

y = np.array([1,2,0,4,0,5,0,0,11])  def test1(y):      x = np.arange(len(y))     idx = np.nonzero(y)     interp = interp1d(x[idx],y[idx])      return interp(x)  def test2(y):     s = pd.series(y)     s.interpolate(inplace=true)     return s.values  %timeit t1 = test1(y) %timeit t2 = test2(y)  139 µs ± 1.62 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 158 µs ± 2.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 

about 12% faster. not hoped, since code going run several million times, worth effort.

i think implementation bit off. want closer @thomas came with:

y = np.array([1,2,0,4,0,5,0,0,11]) idx = np.nonzero(y) interp = interp1d(x[idx],y[idx])  x = np.arange(len(y)) ynew = interp(x) 

if want re-construct original array interp, need use .x , .y parameters.

a_ = np.zeros(interp.x[-1] + 1) a_[interp.x] = interp.y 

of course, remove trailing zeros original a, a.size not preserved in interpolation. if have preserved them elsewhere (such ynew.shape), can instead initialize a_ = np.zeros_like(ynew)


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -