Given a list of tuples, [(x1, y1), (x2, y2) ... (xm, ym)]
such as [(1, 2), (3, 7), (5, 9)]
I would like to write a function that fills in the missing integer values x with the average of the neighbor values f(x - 1), f(x + 1).
In this case, we would get:
[(1, 2), (2, ave(2, 7)), (3, 7), (4, ave(7, 9)), (5, 9)]
import numpy as np
# calculating nearest neighbor averages
def nearest(x, y):
# define the min and max for our line
min = np.amin(x)
max = np.amax(x)
# fill in the gaps
numsteps = max - min + 1
# an empty vessel
new_df = []
# an empty vessel for our xs
xs = np.linspace(min, max, numsteps)
for i, item in enumerate(xs):
if(xs[i] in x):
idx = x.index(xs[i])
new_df.insert(i, (xs[i], y[idx]))
else:
idx = x.index(xs[i] - 1)
idx2 = x.index(xs[i] + 1)
avg = (y[idx] + y[idx2])/2.0
new_df.insert(i, (xs[i], avg))
print new_df
nearest([1, 3, 5], [6, 7, 8])
// [(1.0, 6), (2.0, 6.5), (3.0, 7), (4.0, 7.5), (5.0, 8)]
This quickly fails, however, with an array such as xs = [1, 4, 7]
, since the values are more than one away from each other. In that case, given the same ys = [2, 7, 9]
, we would expect the answer to either be:
[(1, 2), (2, ave(2, 7)), (3, ave(2,7)), (4, 7) ... ]
or
Something a bit more complicated:
[(1, 2), (2, ave(prev, next_that_exists)), (3, ave(just_created, next_that exists), ...]
How can I implement so that we find the elements just below the missing one and just above the missing one, and compute their average?
Also, is this different from a moving average?