python 14 lines · 1 tab

Time series resampling and rolling windows in pandas

1 tab
import pandas as pd

df = pd.read_csv('traffic.csv', parse_dates=['timestamp'])
df['timestamp'] = pd.to_datetime(df['timestamp'], utc=True)
df = df.set_index('timestamp').sort_index()

hourly = df.resample('1H').agg({'requests': 'sum', 'errors': 'sum'})
hourly['error_rate'] = hourly['errors'] / hourly['requests'].clip(lower=1)
hourly['requests_24h_mean'] = hourly['requests'].rolling('24H').mean()
hourly['requests_24h_std'] = hourly['requests'].rolling('24H').std()
hourly['requests_lag_1h'] = hourly['requests'].shift(1)
hourly['requests_growth'] = hourly['requests'].pct_change()

print(hourly.tail(10))
1 file · python Explain with highlit

For operational metrics and forecasting features, I standardize timestamps first and then resample into stable windows. Rolling statistics like 7D means, lagged deltas, and volatility bands are easy wins for exploratory analysis. I avoid mixing timezone-naive and timezone-aware timestamps because it becomes a debugging tax later.

Share this code

Here's the card — post it anywhere.

Time series resampling and rolling windows in pandas — share card
Link copied