Sessionize Clickstream Events With a Thirty Minute Inactivity Gap
Last updated: November 29, 2026
Quick Overview
Using pandas, assign a session id to each event in a clickstream DataFrame where a new session starts after more than 30 minutes of inactivity per user, then produce per-session duration, event count, and whether a purchase happened.
Amazon
November 29, 20260
0
0 solved
Using pandas, assign a session id to each event in a clickstream DataFrame where a new session starts after more than 30 minutes of inactivity per user, then produce per-session duration, event count, and whether a purchase happened.
Session metrics feed conversion analysis across Amazon retail surfaces, and Python data manipulation rounds for Data Scientists often use pandas on event logs. The interviewer checks vectorized group-wise operations rather than Python loops, and correct handling of ordering and boundaries.
What the Interviewer Expects
- Sort by user and timestamp before computing gaps
- Use groupby diff and cumsum to number sessions
- Define the boundary precisely (strictly greater than 30 minutes)
- Aggregate with named aggregations
- Avoid row-by-row loops
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you do the same in SQL?
- How would you split sessions that cross midnight for daily reporting?
- How would you also cap sessions at 4 hours?
- How would you scale this to billions of events?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
DataFrame events with columns user_id, ts (datetime64), event (for example view, add_to_cart, purchase). Events may be unsorted. A new session begins at a user's first event or when the ...
Approach
- Sort by
user_id,ts. - Compute the gap to the previous event within each user with
groupby().diff(); the first event per user hasNaT. - Mark new sessions where gap is
NaTor above 30 m...