How to calculate rolling / moving average using python + NumPy / SciPy? discusses the situation when the observations are equally spaced, i.e., the index is equivalent to an integer range.
In my case, the observations come at arbitrary times and the interval between them can be an arbitrary float. E.g.,
import pandas as pd
import numpy as np
df = pd.DataFrame({"y":np.random.uniform(size=100)}, index=np.random.uniform(size=100)).sort_index()
I want to add a column yavg
to df
whose value at a give index value x0
is
sum(df.y[x]*f(x0-x) for x in df.index) / sum(f(x0-x) for x in df.index)
for a given function f
, e.g.,
def f(x):
return np.exp(-x*x)
How do I do this with a minimal effort (preferably in pure numpy
)?