I have a ragged (meaning not-a-regular frequency), time-indexed DataFrame, that I would like to perform a time-weighted rolling average on, that maintains the original index of the DataFrame. It is assumed that a recorded value is valid until superseded by another value. One way to achieve this is by just up-sampling the the ragged DataFrame to a uniform frequency and then do a rolling mean:
import pandas as pd
import numpy as np
def time_weighted_average_using_upsampling(df: pd.DataFrame, avg_window: str) -> pd.DataFrame:
# Leads to high memory usage
original_index = df.index.copy()
avg = (
df.resample("1s")
.ffill()
.rolling(avg_window, closed="left", min_periods=int(avg_window[0])))
.mean()
.reindex(original_index)
)
return avg
if __name__ == "__main__":
df = pd.DataFrame(
{"A": [0, 1, 2, 3, 4, 5]},
index=[
pd.Timestamp("20130101 09:00:00"),
pd.Timestamp("20130101 09:00:02"),
pd.Timestamp("20130101 09:00:03"),
pd.Timestamp("20130101 09:00:05"),
pd.Timestamp("20130101 09:00:06"),
pd.Timestamp("20130101 09:00:10"),
],
)
expected_avg = pd.DataFrame(
{"A": [np.nan, np.nan, 1 / 3, 5 / 3, 7 / 3, 4]},
index=[
pd.Timestamp("20130101 09:00:00"),
pd.Timestamp("20130101 09:00:02"),
pd.Timestamp("20130101 09:00:03"),
pd.Timestamp("20130101 09:00:05"),
pd.Timestamp("20130101 09:00:06"),
pd.Timestamp("20130101 09:00:10"),
],
)
pd.testing.assert_frame_equal(
time_weighted_average_using_upsampling(df=df, avg_window="3s"), expected_avg
)
The issue with this is that the up-sampling defeats the purpose of the sparse representation that the ragged df offers. A sparse representation is memory efficient, while the up-sampled version is not. This begs the question: How does one achieve the result shown above without having to up-sample the entire df?