UPDATE: Here's how to do it with numpy interp :
import numpy as np myList = [26, None, None, None, 31, None, None, 58, None, 42, None, None, None, 79] values = [(i, val) for i, val in enumerate(myList) if val is not None] xp, fp = zip(*values) print(xp)
Original post:
As others have said, it is best to use some interpolation already implemented in numpy or pandas.
However, for completeness, here was a quick solution that I came up with:
myList = [26, None, None, None, 31, None, None, 58, None, 42, None, None, None, 79] resultList = [] # first lets split the list into sublists that group the numbers # and the Nones into groups for i, item in enumerate(myList): if i == 0: resultList.append([item]) else: if type(resultList[-1][-1]) == type(item): resultList[-1].append(item) else: resultList.append([item]) print(resultList) # [[26], [None, None, None], [31], [None, None], [58], [None], [42], [None, None, None], [79]] # now lets interpolate the sublists that contain Nones for i, item in enumerate(resultList): if item[0] is not None: continue # this is a bit problematic, what do we do if we have a None at the beginning or at the end? if i == 0 or i + 1 == len(resultList): continue prev_item = resultList[i - 1][-1] next_item = resultList[i + 1][0] difference = next_item - prev_item item_length = len(item) + 1 for j, none_item in enumerate(item): item[j] = prev_item + float(j + 1) / item_length * difference # flatten the list back resultList = [item for sublist in resultList for item in sublist] print(resultList) # [26, 27.25, 28.5, 29.75, 31, 40.0, 49.0, 58, 50.0, 42, 51.25, 60.5, 69.75, 79]
I suggest you use this only for training or for simple cases, since it does not handle cases when you have lists starting or ending with None