0

I create an array of size 50 for example without any value, then I insert let's say 3 values in it at random indexes and then I want to fill the rest of the array by interpolating between those values.

First I create my array:

n = 50
a = [None]*n

which give me an "empty array" of 50 slots:

[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

then I replace manually several "None" randomly chosen with values:

a.pop(0)
a.insert(0,0)
a.pop(10)
a.insert(10,50)
a.pop(49)
a.insert(49,25000)

which give this:

[0, None, None, None, None, None, None, None, None, None, 50, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 25000]

How can I fill the rest of the array, meaning replacing the "Nones" by actual values calculated by linear interpolation between the values I manually added in my array ?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Can you use libraries such as numpy, pandas, scipy? – Mr. T Nov 08 '20 at 19:52
  • Thanks a lot jonrsharpe, Mr.T and ted ! both answers helped me a lot, and I choose the Pandas way, didn't know this library and with it it's simple !! a = pandas.Series(a).interpolate().values.round(2).tolist() Did the job !! – ulysse lefort Nov 09 '20 at 14:34

1 Answers1

0

I'm sure there's a smart way of using scipy's interpolations to do so. But a quick way of solving your problem could be:

import numpy as np

interpolated = np.empty(len(l))
min_i = 0
min_v = 0
for i, v in enumerate(l):
   if v is not None:
       interpolated[min_i: i + 1] = list(np.linspace(min_v, v, i - min_i + 1))
       min_i = i
       min_v = v
interpolated = list(interpolated)
ted
  • 13,596
  • 9
  • 65
  • 107