Resample daily events to weekly totals and add a 4-week rolling average — how?
df has a daily date column and an events integer count. Roll it up to weekly totals (week ending Sunday) and add a 4-week rolling average of that weekly total.
import pandas as pd
def weekly_with_rolling(df: pd.DataFrame) -> pd.DataFrame:
# your code here
Write the implementation.
resample needs a DatetimeIndex, so set_index('date') first, then resample('W')['events'].sum() gives weekly totals (week-ending Sunday). Chain .rolling(4, min_periods=1).mean() for the 4-week average. Unlike a groupby on week number, resample fills empty weeks.
- ✗Calling
resamplewithout a DatetimeIndex and getting a TypeError - ✗Grouping by week number, which drops calendar weeks that had no events
- ✗Running
rollingon the daily rows instead of the weekly series
- →How would you switch the week to end on Monday instead of Sunday?
- →What does
min_periodschange at the start of the rolling window?
resample is a time-aware groupby: it needs a DatetimeIndex, buckets by the rule ('W' = week ending Sunday), and reindexes onto a complete calendar so empty weeks appear as 0. rolling(4) then averages the four most recent weekly totals.
import pandas as pd
def weekly_with_rolling(df: pd.DataFrame) -> pd.DataFrame:
weekly = df.set_index('date').resample('W')['events'].sum()
out = weekly.to_frame('events')
out['events_4w'] = out['events'].rolling(4, min_periods=1).mean()
return out
min_periods=1 averages what is available at the start instead of returning NaN for the first three weeks. Use resample('W-MON') to end weeks on Monday.