Flatten Event Logs and Build User Segments in pandas
SQL & DataModel answerLast 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 loggedevents(list of dicts): each dict has atype, atsstring, and optionally anamountattrs(dict): client attributes such asversionand a nestedflagsdict containingbetaanddark
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.
- 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. UseSeries.explodeandapply/lambdato parse the dicts. - 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. Usegroupbywith named aggregations. If a user has several different attribute values over time, use the attributes belonging to their most recent event. - Segment conversion. A segment is the triple
(version_most_recent, beta_flag_most_recent, dark_flag_most_recent). Return one row per segment with columnsversion, beta_flag, dark_flag, users, purchasers, conversion_rate, where the rate is the fraction of users in the segment who made purchases. - 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 avoidsSettingWithCopyWarningand 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the work into two phases: flatten once into typed columns, then do everything else with ordinary vectorized grouping on flat data.
Phase 1: flatten
explode("events")gives one row per event and repeatsuser_id,tsandattrs. Each event therefore carries the attributes of the log row it came from, which is what makes "attributes of the most recent event" well defined.- An empty list or NaN explodes into a single NaN row. Filter to elements where
isinstance(e, dict)so these never count as events. - Parse each field with a single
Series.applyover one object column, and assemble the result with.assign. Convert to proper dtypes:datetime64for time,Float64for amount,booleanfor flags,stringfor type and version. - If an event's own
tsis missing or malformed,pd.to_datetime(..., errors="coerce")yields NaT, which we fill from the row-levelts. Ordering then still works.
Phase 2: aggregate
- Sort by
(user_id, event_ts)with a stable sort (kind="mergesort"), so timestamp ties keep original row order. - Create 0/1 indicator columns for click, view and purchase, plus a
purchase_amountcolumn that is the amount only where the event is a purchase. Then a singlegroupby("user_id").agg(click_count=("is_click","sum"), ...)yields counts,last_event_ts(max) andtotal_purchase_amount(sum, which is 0.0 for users with no purchases). - For the most recent attributes, do not use
groupby().last(). It skips nulls column by column, so if the newest event hasversion=Noneit quietly returns an older version, and the three attributes may come from different events. Instead takedrop_duplicates("user_id", keep="last")on the sorted frame and join those three columns to the aggregates. - Segment conversion:
groupby([...], dropna=False)over the features table, withusers = size,purchasers = (purchase_count > 0).sum(), andconversion_rate = purchasers / users.
Ambiguity to call out
"purchases/users" is read as purchasers / users, the share of users in the segment with at least one purchase, because the required output has a purchasers column. Total purchase count divided by users would be a different metric (purchases per user). Say this explicitly and note it is a one-line change.
Code
import pandas as pd
def get_nested(obj, path, default=None):
"""Walk `path` (tuple of keys) through nested dicts.
Returns `default` if any level is missing, None, or not a dict."""
cur = obj
for key in path: # plain dict iteration
if not isinstance(cur, dict) or key not in cur:
return default
cur = cur[key]
return default if cur is None else cur
# Why this avoids SettingWithCopy and stays vectorized:
# - explode / loc / assign all return NEW frames; we never write into a
# slice (no df[mask]["c"] = ...), so there is no chained assignment
# and the input df is never mutated.
# - .assign(col=lambda x: ...) binds to the intermediate frame, not a stale view.
# - Per-element Python work is one .apply per object column; afterwards all
# columns have real dtypes, so sort/filter/groupby run in C.
def explode_events(df):
ex = df[["user_id", "ts", "events", "attrs"]].explode("events", ignore_index=True)
ex = ex.loc[ex["events"].apply(lambda e: isinstance(e, dict))]
out = ex.assign(
event_type=lambda x: x["events"].apply(lambda e: e.get("type")).astype("string"),
event_ts=lambda x: pd.to_datetime(
x["events"].apply(lambda e: e.get("ts")), errors="coerce"
).fillna(x["ts"]),
amount=lambda x: pd.to_numeric(
x["events"].apply(lambda e: e.get("amount")), errors="coerce"
).astype("Float64"),
attrs_version=lambda x: x["attrs"].apply(lambda a: get_nested(a, ("version",))).astype("string"),
attrs_beta_flag=lambda x: x["attrs"].apply(lambda a: get_nested(a, ("flags", "beta"))).astype("boolean"),
attrs_dark_flag=lambda x: x["attrs"].apply(lambda a: get_nested(a, ("flags", "dark"))).astype("boolean"),
)
cols = ["user_id", "event_type", "event_ts", "amount",
"attrs_version", "attrs_beta_flag", "attrs_dark_flag"]
return out[cols].reset_index(drop=True)
def build_features(ev):
s = ev.sort_values(["user_id", "event_ts"], kind="mergesort", na_position="first")
s = s.assign(
is_click=s["event_type"].eq("click").fillna(False).astype(int),
is_view=s["event_type"].eq("view").fillna(False).astype(int),
is_purchase=s["event_type"].eq("purchase").fillna(False).astype(int),
)
s = s.assign(purchase_amount=s["amount"].where(s["is_purchase"] == 1))
agg = s.groupby("user_id").agg(
click_count=("is_click", "sum"),
view_count=("is_view", "sum"),
purchase_count=("is_purchase", "sum"),
last_event_ts=("event_ts", "max"),
total_purchase_amount=("purchase_amount", "sum"),
)
recent = (s.drop_duplicates("user_id", keep="last")
.set_index("user_id")[["attrs_version", "attrs_beta_flag", "attrs_dark_flag"]]
.rename(columns={"attrs_version": "version_most_recent",
"attrs_beta_flag": "beta_flag_most_recent",
"attrs_dark_flag": "dark_flag_most_recent"}))
return agg.join(recent)
def segment_conversion(feat):
keys = ["version_most_recent", "beta_flag_most_recent", "dark_flag_most_recent"]
seg = (feat.assign(is_purchaser=feat["purchase_count"].gt(0))
.groupby(keys, dropna=False)
.agg(users=("is_purchaser", "size"),
purchasers=("is_purchaser", "sum"))
.reset_index()
.rename(columns={"version_most_recent": "version",
"beta_flag_most_recent": "beta_flag",
"dark_flag_most_recent": "dark_flag"}))
seg["conversion_rate"] = seg["purchasers"] / seg["users"]
return seg
Complexity
With E events and U users: explode and parse is O(E) with a real Python-call constant, the sort is O(E log E), group-bys are O(E) and O(U), and memory is O(E). For large data, pd.json_normalize(exploded["events"].tolist()) parses all event keys in one pass and is usually faster than several apply calls.
Edge cases
eventsis None, NaN or[]: no event rows are produced. If such users must appear in the denominators, reindex features ondf.user_id.unique(), fill counts with 0, and take attributes from their latestdfrow.attrsNone,flagsmissing or not a dict: the helper returns the default, so the value becomes null rather than raising.- Amount on non-purchases or missing on purchases: only purchase amounts are summed; users with no purchases get 0.0.
- Malformed event
ts: coerced to NaT, then filled from the rowts. - Null segment keys:
dropna=Falsekeeps them as their own segment.
Common mistakes
- Using
groupby().last()for the latest attributes (skips nulls, mixes events). - Writing to a filtered slice, causing
SettingWithCopyWarning. - Leaving columns as
objectdtype so sorting and aggregation are slow or wrong. - Dividing total purchases by users when purchasers by users was intended, without stating the assumption.
- Letting empty event lists become phantom NaN events that inflate counts.