KatInterview

Flatten Event Logs and Build User Segments in pandas

SQL & DataModel answer
MediumModel answerSQL & Datapandasdata-manipulationexplode

Last updated

Turn a table of nested event lists and attribute dicts into a flat event table, per-user features, and segment conversion rates using pandas without row loops.

You have a pandas DataFrame df of app activity logs with these columns:

  • user_id (int)
  • ts (datetime64[ns]): the time the row was logged
  • events (list of dicts): each dict has a type, a ts string, and optionally an amount
  • attrs (dict): client attributes such as version and a nested flags dict containing beta and dark

Example rows:

user_id=1, ts=2025-08-08 09:12:00,
  events=[{"type":"click","ts":"2025-08-08T09:12:00"},
          {"type":"view","ts":"2025-08-08T09:12:05"}],
  attrs={"version":"1.2.0","flags":{"beta":True,"dark":False}}

user_id=1, ts=2025-08-09 15:00:00,
  events=[{"type":"purchase","ts":"2025-08-09T15:00:00","amount":20.0}],
  attrs={"version":"1.2.0","flags":{"beta":True,"dark":False}}

user_id=2, ts=2025-08-04 12:30:00,
  events=[{"type":"view","ts":"2025-08-04T12:30:00"}],
  attrs={"version":"1.1.0","flags":{"beta":False,"dark":True}}

Write Python/pandas code for the following. Do not loop over DataFrame rows with for, iterrows or similar.

  1. Flatten events. Produce a long table with one row per event and columns user_id, event_type, event_ts (datetime), amount (nullable), attrs_version, attrs_beta_flag, attrs_dark_flag. Use Series.explode and apply/lambda to parse the dicts.
  2. Per-user features. Produce one row per user with click_count, view_count, purchase_count, last_event_ts, total_purchase_amount, version_most_recent, beta_flag_most_recent, dark_flag_most_recent. Use groupby with named aggregations. If a user has several different attribute values over time, use the attributes belonging to their most recent event.
  3. Segment conversion. A segment is the triple (version_most_recent, beta_flag_most_recent, dark_flag_most_recent). Return one row per segment with columns version, beta_flag, dark_flag, users, purchasers, conversion_rate, where the rate is the fraction of users in the segment who made purchases.
  4. Safe nested getter. Write a helper, used inside a lambda, that walks a path of keys through nested dicts and tolerates missing keys and None. In comments, explain why your approach avoids SettingWithCopyWarning and stays vectorized.

State any ambiguity you notice and how you resolve it. Cover empty or missing events, missing attrs/flags, and events with no timestamp.

Hints

Hint 1

Explode the `events` column first, then keep only elements that are actually dicts, so empty lists and NaN do not turn into fake events. Because explode repeats the other columns, each event keeps the `attrs` of its source row.

Hint 2

Be careful with `groupby().last()`: it returns the last non-null value for each column independently, so attributes could come from different events. Sort by user and event time and use `drop_duplicates('user_id', keep='last')` to take all three attributes from one row.

Hint 3

The phrase 'purchases/users' is ambiguous. Since the output has a `purchasers` column, compute purchasers divided by users (share of users with at least one purchase). Use `groupby(..., dropna=False)` so users with missing attributes still form a segment.

Hint 4

Build columns with `.assign(...)` on new frames rather than writing into filtered slices, and convert parsed columns to proper dtypes (`datetime64`, `Float64`, `boolean`, `string`) so later steps are vectorized.