Banner CTR and Session Change Analysis in Pandas
SQL & DataModel answerLast updated
Clean a click-stream with pandas to compute daily banner CTR without bots or accidental clicks, user-level CTR by signup cohort, and per-user session-length change around a feature launch.
Banner and Story Metrics with Pandas
You are analysing event logs for a social app. Use pandas only, with no Python loops over rows. Treat "today" as 2025-09-01, and define "the last 7 days" as 2025-08-26 through 2025-09-01 inclusive (UTC).
Inputs
events
| column | type | notes |
|---|---|---|
event_id | int | unique, increases with time |
user_id | int | |
ts | UTC datetime | |
event_type | string | one of banner_impression, banner_click, story_view, story_post, back_navigation |
banner_id | nullable int | set for banner events |
story_id | nullable int | set for story events |
group_id | nullable int | set for group story posts |
dwell_ms | nullable int | time spent after a click |
users
| column | type |
|---|---|
user_id | int |
is_bot | bool |
signup_dt | date |
Sample of events (event_id, user_id, ts, event_type, banner_id, story_id, group_id, dwell_ms):
1, 10, 2025-08-31T12:00:00Z, banner_impression, 7, null, null, null
2, 10, 2025-08-31T12:00:01Z, banner_click, 7, null, null, 200
3, 10, 2025-08-31T12:00:02Z, back_navigation, null, null, null, null
4, 11, 2025-08-31T13:00:00Z, banner_impression, 7, null, null, null
5, 11, 2025-08-31T13:00:05Z, banner_click, 7, null, null, 1200
6, 12, 2025-08-29T09:00:00Z, story_post, null, 101, 5, null
Tasks
- Accidental clicks. A
banner_clickis accidental ifdwell_ms < 500, or if the same user has aback_navigationevent within 2 seconds after the click. Accidental clicks must not count toward CTR. - Daily banner CTR. For the last 7 days, excluding bot users and accidental clicks, output one row per
(date, banner_id)withdate, banner_id, impressions, valid_clicks, ctr. - User-level CTR. Compute each user's CTR over the same 7 days with the same exclusions, then summarise its distribution by signup cohort (the week of
signup_dt). - Session change for the Group Story feature. Compare a pre-period (2025-08-18 to 2025-08-24) with a post-period (2025-08-25 to 2025-09-01). A session is a run of a user's events (any type) with no gap longer than 30 minutes. Output
user_id, pre_avg_minutes, post_avg_minutes, delta_minutes, stories_posted_change. - Engineering quality. Use vectorised operations (
groupby, window functions,merge_asof), keep dtypes stable, and avoidSettingWithCopyWarning. Explain which indices you would set and how you would verify correctness on the sample above.
Write the code and explain your reasoning, including the assumptions you make for ambiguous cases.
Hints
Hint 1
Clean and sort the whole event table once (tz-aware UTC timestamps, nullable integer IDs, stable sort by timestamp then event_id) before any windowing, because merge_asof needs a sorted key and a click near midnight may be followed by a back-navigation on the next day.
Hint 2
Match each click to the next back_navigation by the same user using merge_asof with by='user_id', direction='forward' and a 2-second tolerance. Handle null dwell_ms explicitly so that a missing value does not count as a short dwell.
Hint 3
Use a half-open window [2025-08-26, 2025-09-02) so the last day is included. Count impressions and valid clicks separately, then align them. For sessions, flag a new session when the gap to the user's previous event exceeds 30 minutes, take a cumulative sum for session IDs, and assign each session to the period that contains its start.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build every metric from one cleaned, globally sorted event table, then aggregate with groupby. Nothing needs a Python loop.
1. Normalise once
- Parse
tsas tz-aware UTC. - Cast nullable ID and dwell columns to
Int64, so nulls survive without being turned into floats. - Drop users flagged as bots. Users missing from
usersare treated as non-bots; state this assumption. - Sort by
(ts, event_id)with a stable sort. This makes ties deterministic and satisfiesmerge_asof.
2. Flag accidental clicks
Do this on the full table, before applying the date window. Otherwise a click at 23:59:59 on 09-01 would miss a back-navigation at 00:00:01 on 09-02.
- Take the click rows and the back-navigation rows (renaming the back timestamp to
back_ts). pd.merge_asof(clicks, backs, on="ts", by="user_id", direction="forward", tolerance=pd.Timedelta("2s")). This returns, for each click, the nearest back-navigation by the same user at or after the click and within 2 seconds. A non-nullback_tsmeans "quick back".low_dwell = dwell_ms.lt(500).fillna(False). A missing dwell does not make the click accidental.accidental = low_dwell | quick_back; valid clicks are the rest.
On the sample: click 2 has dwell 200 (and a back-nav 1 second later), so it is accidental. Click 5 has dwell 1200 and no back-nav, so it is valid.
3. Daily banner CTR
- Window:
ts >= 2025-08-26 00:00Zandts < 2025-09-02 00:00Z. The half-open end avoids the classic bug of writing<= '2025-09-01', which drops the entire last day. - Add
date = ts.dt.floor("D")(or.dt.date). - Count impressions and valid clicks separately with
groupby(["date","banner_id"]).size(), then outer-join andfillna(0). ctr = valid_clicks / impressions. Zero impressions givesNaN(orinfbefore replacement), never an exception; convert toNaNexplicitly.
Sample result: banner 7 on 2025-08-31 has 2 impressions, 1 valid click, CTR 0.5.
4. User-level CTR and cohorts
- Same exclusions, but group by
user_id. - Join
users[["user_id","signup_dt"]]and computecohort = signup_dt.dt.to_period("W").dt.start_time. - Report both:
- Pooled CTR per cohort:
sum(valid_clicks) / sum(impressions). - Distribution of per-user CTR:
describeor quantiles (p10, p50, p90) per cohort, restricted to users with at least one impression.
- Pooled CTR per cohort:
These answer different questions: the pooled number is weighted by impressions, the quantiles describe typical users. Users with few impressions give noisy CTRs, so consider a minimum-impression filter.
5. Sessions and pre/post change
- Sort by
(user_id, ts). Computegap = groupby("user_id")["ts"].diff(). new_session = gap.isna() | (gap > 30min). The condition is strictly greater than; a gap of exactly 30 minutes stays in the same session.session_id = new_session.cumsum()gives globally unique IDs.- Aggregate per session:
start = min(ts),end = max(ts),duration_min = (end - start) / 60s. - Assign each session to the period containing its start, so a session crossing the boundary is counted once rather than split. Pre is
[08-18, 08-25), post is[08-25, 09-02). - Pivot to per-user
pre_avg_minutesandpost_avg_minutes, thendelta = post - pre. stories_posted_change: countstory_postevents per user in each period, fill missing with 0, subtract. Note that pre is 7 days and post is 8 days, so raw counts are biased upward for post. Offer posts per day as a normalised alternative.
Edge cases
- Users active in only one period get
NaNfor the other average and thereforeNaNdelta; story counts fill with 0. - A single-event session has duration 0.
- Null
banner_idrows drop out of the bannergroupby. - Clicks without a matching impression can push CTR above 1. Do not clip; flag it as a logging issue.
- A back-navigation at the same timestamp as the click counts (
allow_exact_matches=True, which is the default). - Users missing
signup_dtfall out of the cohort table.
Code sketch
import pandas as pd
WIN_START = pd.Timestamp("2025-08-26", tz="UTC")
WIN_END = pd.Timestamp("2025-09-02", tz="UTC") # exclusive
PRE_START = pd.Timestamp("2025-08-18", tz="UTC")
SPLIT = pd.Timestamp("2025-08-25", tz="UTC")
def prepare(events, users):
ev = events.assign(
ts=pd.to_datetime(events["ts"], utc=True),
banner_id=events["banner_id"].astype("Int64"),
dwell_ms=events["dwell_ms"].astype("Int64"),
)
bots = users.loc[users["is_bot"], "user_id"]
ev = ev[~ev["user_id"].isin(bots)]
return ev.sort_values(["ts", "event_id"], kind="mergesort").reset_index(drop=True)
def flag_clicks(ev):
clicks = ev.loc[ev.event_type == "banner_click",
["event_id", "user_id", "ts", "banner_id", "dwell_ms"]]
backs = (ev.loc[ev.event_type == "back_navigation", ["user_id", "ts"]]
.assign(back_ts=lambda d: d["ts"]))
m = pd.merge_asof(clicks, backs, on="ts", by="user_id",
direction="forward", tolerance=pd.Timedelta("2s"))
bad = m["dwell_ms"].lt(500).fillna(False).astype(bool) | m["back_ts"].notna()
return m.loc[~bad].drop(columns="back_ts")
def daily_ctr(ev):
in_win = ev["ts"].ge(WIN_START) & ev["ts"].lt(WIN_END)
imps = (ev[in_win & (ev.event_type == "banner_impression")]
.groupby([ev["ts"].dt.floor("D").rename("date"), "banner_id"]).size()
.rename("impressions"))
vc = flag_clicks(ev)
vc = vc[vc["ts"].ge(WIN_START) & vc["ts"].lt(WIN_END)]
clicks = (vc.groupby([vc["ts"].dt.floor("D").rename("date"), "banner_id"]).size()
.rename("valid_clicks"))
out = pd.concat([imps, clicks], axis=1).fillna(0).astype("int64").reset_index()
out["ctr"] = out["valid_clicks"] / out["impressions"].where(out["impressions"] > 0)
return out
def sessions(ev):
s = ev.sort_values(["user_id", "ts"]).copy()
gap = s.groupby("user_id")["ts"].diff()
s["sid"] = (gap.isna() | gap.gt(pd.Timedelta("30min"))).cumsum()
g = s.groupby("sid").agg(user_id=("user_id", "first"),
start=("ts", "min"), end=("ts", "max"))
g["minutes"] = (g["end"] - g["start"]).dt.total_seconds() / 60
return g
Period assignment then uses start against [PRE_START, SPLIT) and [SPLIT, WIN_END), followed by a groupby(["user_id","period"]).minutes.mean().unstack().
Complexity
Time is O(N log N), dominated by sorting; merge_asof, diff, cumsum and groupby are linear. Space is O(N).
Indices and testing
- For lookups and joins, set
usersindexed byuser_id. Keepeventssorted byts; avoid a long-lived index on it becausemerge_asoftakes columns. - Test on the sample: assert banner 7 on 08-31 gives
impressions=2, valid_clicks=1, ctr=0.5; add synthetic cases for a click exactly 2.0s before a back-nav (accidental), 2.001s (valid), null dwell (valid), a bot user (excluded), a click at 23:59:59 on 09-01 with back-nav next day, a gap of exactly 30 minutes (same session) and 30:01 (new session). - Assert dtypes (
Int64IDs, tz-awarets) and run withpd.options.mode.chained_assignment = "raise"to catchSettingWithCopyissues.
Common mistakes
- Applying the date filter before the back-navigation match.
- Using
<= '2025-09-01'and losing the last day. - Treating null dwell as under 500 ms.
- Computing CTR as a mean of ratios when a pooled ratio is wanted (and vice versa).
- Ignoring that the pre and post windows have different lengths.