We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Resample Aggregations

As you'd expect, you can apply any aggregation function after resampling:

purchases = events[events["event_type"] == "purchase"]
purchases = purchases.set_index("timestamp")
weekly_avg_order = purchases["amount"].resample("W").mean()
print(weekly_avg_order)

Which prints:

timestamp
2023-12-31    29.99
2024-01-07    39.99
Freq: W-SUN, Name: amount, dtype: float64

The agg() method allows you to compute several statistics at once:

weekly_stats = purchases["amount"].resample("W").agg(["sum", "mean", "count"])
print(weekly_stats)

Which prints:

               sum   mean  count
timestamp
2023-12-31   29.99  29.99      1
2024-01-07  159.96  39.99      4

Counting Events With a Marker

What if your events don't have a numeric column to total up? A raw event log might only have a timestamp, a user_id, and an event_type – nothing to sum or average.

The trick is to add a marker: give every event the value 1, then aggregate those 1s.

indexed = events.set_index("timestamp")
markers = pd.Series(1, index=indexed.index)
daily_counts = markers.resample("D").sum()
print(daily_counts)
timestamp
2023-12-30    1
2023-12-31    0
2024-01-01    2
2024-01-02    1
2024-01-03    1
Freq: D, dtype: int64

Because every marker is a 1:

  • sum adds the 1s together, which is just the number of events in that bucket
  • count counts the rows, which is also the number of events in that bucket
  • mean averages the 1s, so it's 1.0 for any bucket that has events (every value is a 1)

Filling Gaps

Some days may have zero purchases (sad day for business). By default, .sum() fills those empty periods with 0:

daily_revenue = purchases["amount"].resample("D").sum()
print(daily_revenue)

Which prints something like:

timestamp
2023-12-30    29.99
2023-12-31     0.00
2024-01-01    59.98
2024-01-02    19.99
2024-01-03    79.99
Freq: D, Name: amount, dtype: float64

If you want NaN for empty periods (to distinguish "no purchases happened" from an actual $0 total), use min_count=1:

daily_revenue_nan = purchases["amount"].resample("D").sum(min_count=1)
print(daily_revenue_nan)
timestamp
2023-12-30    29.99
2023-12-31      NaN
2024-01-01    59.98
2024-01-02    19.99
2024-01-03    79.99
Freq: D, Name: amount, dtype: float64

Assignment

SnackStack's analytics dashboard wants a weekly summary of device-event volume.

Complete the get_weekly_event_stats function. It accepts an events DataFrame with a timestamp column and returns a DataFrame of weekly event stats (sum, mean, and count), one row per week.