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
Data Manipulation (SQL/Python)
Data Scientist
Meta
November 29, 2026
Data Scientist
Technical Screen
Data Manipulation (SQL/Python)
Medium

0

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
pandas groupby
Sessionization
cumsum trick
Time deltas
Vectorization
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. 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 Problems
Sample 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
  1. Sort by user_id, ts.
  2. groupby('user_id')['ts'].diff() gives the gap to the previous event of the same user (NaT for the first).
  3. A boolean is_new flags session starts; a cumulative sum ...

Submit Your Answer
Markdown supported