Pandas Activity Metrics: Local Dates, Rolling Windows, Retention
SQL & DataModel answerLast updated
Build daily active users, rolling averages, per-user rolling counts and week-over-week retention from a UTC event log, using timezone-correct, vectorized Pandas.
You have a Pandas DataFrame events with columns user_id, event_type, ts_utc and revenue. Each row is one logged user action. The timestamps are recorded in UTC, but the business reports in Los Angeles time (America/Los_Angeles).
Write idiomatic, vectorized Pandas code (no explicit Python loops over rows or users) that does the following:
- Timestamps. Parse
ts_utcas timezone-aware values, convert them to Los Angeles local time, and make sure daylight saving transitions do not produce wrong or ambiguous days. - Daily active users. Count distinct active users per local calendar day, then add a 7-day moving average of that series.
- Per-user rolling counts. For every
(user_id, event_type)pair, compute a rolling 7-day count of events. - Weekly retention. For each week
w, report how many users active in weekwwere also active in weekw+1, and the corresponding rate (retained users divided by users active inw). - Gap filling. Make the daily output cover every calendar date in the observed range, with zeros on days that had no activity.
In your answer, explain your design choices (especially around DST, window definitions and the final incomplete week), state the complexity, and list the edge cases you would check.
Hints
Hint 1
Pick one canonical 'local calendar date' column right after converting from UTC, and build every metric from it. Converting from UTC to a zone is never ambiguous.
Hint 2
Order matters for the moving average: aggregate per day, fill missing days with zeros, and only then roll. Otherwise a 7-row window can span more than 7 calendar days.
Hint 3
For retention, deduplicate (user, week), make a copy with the week shifted back by one, and left-merge it onto the original. A match means the user returned in the next week.
Hint 4
Think about what the last observed week should show: its following week has not been observed, so the retention there is unknown rather than zero.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Everything hinges on one decision: derive a single local calendar date column and compute every metric from it.
- Parse and convert. Use
pd.to_datetime(..., utc=True, errors="coerce"), then.dt.tz_convert("America/Los_Angeles"). Going from UTC to a local zone is always unambiguous, since every instant maps to exactly one wall-clock time. The tz database handles the 23-hour spring-forward day and the 25-hour fall-back day. For example,2024-03-10 09:30Zis01:30 PSTand10:30Zis03:30 PDT. - Make a tz-naive date. After converting, drop the timezone and normalize to midnight. Days are then uniform steps, so
"7D"means seven calendar dates. On a tz-aware index,"7D"means 168 elapsed hours, which is off by an hour around DST. - Aggregate, fill, then roll. Compute DAU with
nunique, resample to daily frequency filling zeros, and only then applyrolling(7). - Retention by self-merge. Convert each date to a weekly
Period, deduplicate(user, week), shift a copy back one week, and left-merge. A hit means the user was active inw+1.
Code
import numpy as np
import pandas as pd
TZ = "America/Los_Angeles"
def prepare(events):
df = events.copy()
df["ts_utc"] = pd.to_datetime(df["ts_utc"], utc=True, errors="coerce")
df = df.dropna(subset=["ts_utc"])
df["ts_local"] = df["ts_utc"].dt.tz_convert(TZ)
df["date"] = df["ts_local"].dt.tz_localize(None).dt.normalize()
df["revenue"] = pd.to_numeric(df["revenue"], errors="coerce").fillna(0.0)
return df
def daily_metrics(df):
daily = (df.groupby("date")
.agg(dau=("user_id", "nunique"),
events=("user_id", "size"),
revenue=("revenue", "sum"))
.resample("D")
.asfreq(fill_value=0))
daily["dau_7d_ma"] = daily["dau"].rolling(7, min_periods=7).mean()
return daily
def rolling_user_event_counts(df):
d = (df.groupby(["user_id", "event_type", "date"]).size()
.rename("n").reset_index()
.sort_values(["user_id", "event_type", "date"])
.set_index("date"))
return (d.groupby(["user_id", "event_type"])["n"]
.rolling("7D").sum().astype("int64")
.rename("count_7d").reset_index())
def weekly_retention(df):
uw = (df.assign(week=df["date"].dt.to_period("W-SUN"))
[["user_id", "week"]].drop_duplicates())
nxt = uw.assign(week=uw["week"] - 1, returned=1)
m = uw.merge(nxt, on=["user_id", "week"], how="left")
m["returned"] = m["returned"].fillna(0)
weeks = pd.period_range(uw["week"].min(), uw["week"].max(),
freq="W-SUN", name="week")
out = (m.groupby("week")
.agg(active_users=("user_id", "size"),
retained_users=("returned", "sum"))
.reindex(weeks, fill_value=0).astype(float))
out["retention_rate"] = out["retained_users"] / out["active_users"].replace(0, np.nan)
out.loc[out.index[-1], ["retained_users", "retention_rate"]] = np.nan
return out
Why this is correct
- DST. Because the source is absolute UTC, the skipped 2 a.m. hour and the repeated 1 a.m. hour never create ambiguity. Short and long days each still map to one calendar date.
- Calendar windows. Once the date column is tz-naive, a
"7D"window covers exactly today plus the six prior calendar dates, including across the DST weekend. - DAU.
nuniquecounts people, not events. Filling empty days with zeros makesrolling(7)a true 7-day window.min_periods=7leaves the first six days as NaN rather than averaging a partial window. If a warm-up value is preferred, usemin_periods=1, and say so explicitly. - Per-user rolling count. Time-based rolling is computed only on days where that pair was active, but the window still reaches back six calendar days. This avoids building a dense users x event types x days table.
- Retention. Deduplicating
(user, week)ensures each user counts once per week. Weeks with no activity get a NaN rate instead of a divide-by-zero. The final week is set to NaN because its follow-up week has not been observed; reporting 0% would be misleading.
Complexity
Let n be the number of events, G the number of distinct (user, event_type, date) rows, and D the number of days.
- Time: O(n log n) for grouping and sorting, O(G log G) for the sort before the rolling step, and linear passes for the windowed sums and the retention merge.
- Space: O(n + G + D). The sparse rolling output avoids the O(users x event types x days) blow-up.
Trade-offs and common mistakes
- Rolling before filling gaps, so "7 rows" silently becomes 10 or more calendar days.
- Using a tz-aware index with
"7D", which gives 168-hour windows and shifts counts near DST changes. - Counting events instead of distinct users for DAU, or counting a user twice in a week for retention.
- Treating the last week's retention as 0 instead of unknown.
- Using calendar
Period("W")defaults without stating the week boundary. Here weeks run Monday to Sunday in LA time; a different business definition changes the result.
Edge cases
- Naive local timestamps. If the source is local wall-clock time rather than UTC, you must use
tz_localize(TZ, ambiguous=..., nonexistent="shift_forward"). That is where DST genuinely causes trouble. - Bad data. Unparseable timestamps and non-numeric revenue are coerced, then dropped or zero-filled. Report how many rows were affected.
- Duplicate events. They inflate event counts and rolling counts but not DAU or retention. Dedupe upstream if they are logging errors.
- Empty input.
date_rangeandperiod_rangefail on NaT bounds, so return early. - Sparse users. A user with a single event still gets a valid rolling count. A user inactive in week
w+1is correctly not retained, even if active inw+2.