pythonintermediate

Pandas Rolling & Expanding Windows

Compute moving averages, rolling sums, and cumulative stats on time-series data with pandas.

python
import pandas as pd
import numpy as np

idx = pd.date_range('2024-01-01', periods=365, freq='D')
df = pd.DataFrame({'sales': np.random.randint(100, 500, len(idx))}, index=idx)

df['ma7']  = df['sales'].rolling(7).mean()
df['ma30'] = df['sales'].rolling(30).mean()
df['cumsum'] = df['sales'].expanding().sum()
df['pct_change'] = df['sales'].pct_change()
print(df.tail())

Use Cases

  • sales forecasting
  • metric smoothing
  • time-series analysis

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.