KatInterview

Pandas Activity Metrics: Local Dates, Rolling Windows, Retention

SQL & DataModel answer
MediumModel answerSQL & Datapandastime-seriesgroupby

Last 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:

  1. Timestamps. Parse ts_utc as timezone-aware values, convert them to Los Angeles local time, and make sure daylight saving transitions do not produce wrong or ambiguous days.
  2. Daily active users. Count distinct active users per local calendar day, then add a 7-day moving average of that series.
  3. Per-user rolling counts. For every (user_id, event_type) pair, compute a rolling 7-day count of events.
  4. Weekly retention. For each week w, report how many users active in week w were also active in week w+1, and the corresponding rate (retained users divided by users active in w).
  5. 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.