-1

I am working in Python. I have a vector of values ranging let say from 1 to 10. I want to add missing data (zeros), such the value is linearly interpolated:

value = [2., 1., 0., 0., 0., 1., 1., 0., 0., 0.0001]

I would like to get the missing values (zeros) through linear interpolation:

value = [2., 1., 1., 1., 1., 1., 1., 0.666, 0.333, 0.0001]
  • That's reasonable, and it's not very hard. Do you just want linear interpolation based on the adjacent values? So, you don't actually want to make a "line" from the other points? What have you tried already? – Tim Roberts Nov 30 '21 at 21:09

2 Answers2

1

I shouldn't do this, because it feels like it might be homework, but here is one way to do this:

value = [2., 1., 0., 0., 0., 1., 1., 0., 0., 0.0001]

#value = [2., 1., 1., 1., 1., 1., 1., 0.666, 0.333, 0.0001]

newdata = []
missing = 0
for v in value:
    if v == 0.:
        missing += 1
    else:
        if missing:
            lastgood = newdata[-1]
            incr = (v - lastgood) / (missing + 1)
            for _ in range(missing):
                lastgood += incr
                newdata.append( lastgood )
            missing = 0
        newdata.append( v )
print(newdata)

Output:

[2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.6667000000000001, 0.3334000000000001, 0.0001]

This fails if the dataset either starts or ends with a 0.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

You can use scipy's interpolate

import numpy as np
from scipy.interpolate import interp1d

value = [2., 1., 0., 0., 0., 1., 1., 0., 0., 0.0001]

x = np.linspace(1, len(value), num=len(value))
x1 = [x[i] for i, _ in enumerate(value) if value[i] != 0]
y1 = [v for v in value if v != 0]
f = interp1d(x1, y1)

y = f(x)
michaelgbj
  • 290
  • 1
  • 10