Sessionize Instagram App Events with a Thirty-Minute Gap in Pandas
Last updated: November 29, 2026
Quick Overview
Given a DataFrame of Instagram app events with user_id and timestamp, write pandas code that assigns session numbers using a 30-minute inactivity gap and reports sessions per user and median session length.
Meta
November 29, 20260
0
0 solved
Given a DataFrame of Instagram app events with user_id and timestamp, write pandas code that assigns session numbers using a 30-minute inactivity gap and reports sessions per user and median session length.
Meta data scientists often get a pandas round alongside SQL, and sessionization is a favorite because session counts and lengths underpin engagement metrics for Instagram and Facebook. The interviewer checks vectorized groupby logic instead of Python loops, the exact gap boundary, and sorting.
What the Interviewer Expects
- Sorts by user and timestamp before computing gaps
- Uses groupby diff and a cumulative sum to label sessions
- States whether a gap of exactly 30 minutes starts a new session
- Aggregates session start, end, length, and event count
- Avoids 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 add a maximum session length of four hours?
- Single-event sessions have zero length. How would you treat them?
- How would you do the same in SQL?
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
Input events with columns user_id and ts (datetime64). Events may be unsorted. A new session starts at a user's first event or when the gap from the previous event is greater than 30 minutes...
Approach
- Sort by
user_id,ts. groupby('user_id')['ts'].diff()gives the gap to the previous event of the same user (NaT for the first).- A boolean
is_newflags session starts; a cumulative sum ...