Skip to content

Python interview practice/Python Data Analyst

Split events into sessions

Hardpandas · sessionization · time-series

The problem

Group each user's events into sessions: a new session starts when more than gap_minutes have passed since that user's previous event. Return user, sessions and events, sorted by user.

Function: def sessionize(events,gap_minutes):

Example input (a JSON list of arguments): [[{"user": "u1", "at": "2026-01-01T11:00:00"}, {"user": "u2", "at": "2026-01-01T09:00:00"}, {"user": "u1", "at": "2026-01-01T10:00:00"}, {"user": "u1", "at": "2026-01-01T11:30:00"}, {"user": "u1", "at": "2026-01-01T10:20:00"}], 30]
Expected output: [{"user": "u1", "sessions": 2, "events": 4}, {"user": "u2", "sessions": 1, "events": 1}]

Inputs satisfy the problem statement. Sequences contain at most 200 elements unless a smaller bound is stated. Use JSON values and the supplied function signature.

Hints

  1. Sort by user and time, then take diff() of the timestamps within each user.
  2. Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.

Worked answer

Try it yourself first. When you are ready, open the answer below.

Show the Python answer
def sessionize(events,gap_minutes):
    import pandas as pd
    if not events:return []
    df=pd.DataFrame(events);df['at']=pd.to_datetime(df['at']);df=df.sort_values(['user','at'])
    gap=df.groupby('user')['at'].diff()
    df['start']=gap.isna()|(gap>pd.Timedelta(minutes=gap_minutes))
    out=df.groupby('user').agg(sessions=('start','sum'),events=('at','size')).reset_index()
    return [{"user":r.user,"sessions":int(r.sessions),"events":int(r.events)} for r in out.itertuples()]

Why it works

Sort by user and time, then take diff() of the timestamps within each user. A session starts at each user's first event (the gap is missing) or when the gap is longer than the limit. Summing those start flags per user counts sessions. A gap exactly equal to the limit stays in the same session.

Complexity: O(n log n) time / O(n) space.

Time: O(n log n) time · Space: O(n) space

Run your own solution

Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Python Data Analyst.

See access and price

More free Python Data Analyst questions

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.