0Pricing
Pandas & NumPy Academy · Lesson

Sessionisation and Event Sequencing

Group events by user and session, compute session duration with timestamp arithmetic, and sort events chronologically.

Sessionisation and Event Sequencing is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Understanding Clickstream Data

A clickstream dataset records every user action: page views, button clicks, and purchases — each as a row with a user_id, session_id, event_type, and timestamp. Before computing any metrics, you must understand the schema. Run df.dtypes and df.sample(5) to see representative rows and confirm the timestamp column parsed as datetime rather than string.

import pandas as pd

df = pd.read_csv('clickstream.csv', parse_dates=['timestamp'])
print(df.dtypes)
print(df.sample(5))

Sorting Events Chronologically

Event analysis is meaningless if rows are not in time order. Sort by user_id and then timestamp so all events for the same user appear consecutively and in the correct sequence. Use sort_values(['user_id', 'timestamp']) and reset the index to get a clean integer sequence reflecting the sorted order.

df = df.sort_values(['user_id', 'timestamp']).reset_index(drop=True)
print(df[['user_id', 'session_id', 'event_type', 'timestamp']].head(10))

Defining Session Boundaries

If sessions are not pre-labelled, you can define them by a 30-minute inactivity gap: a new session begins whenever the time since the previous event for the same user exceeds 30 minutes. Use groupby('user_id')['timestamp'].diff() to compute the gap between consecutive events, then flag rows where the gap exceeds the threshold as session starts.

threshold = pd.Timedelta('30min')

df['time_gap'] = df.groupby('user_id')['timestamp'].diff()
df['is_new_session'] = (df['time_gap'] > threshold) | (df['time_gap'].isna())
df['session_id_inferred'] = df.groupby('user_id')['is_new_session'].cumsum()

print(df[['user_id', 'timestamp', 'time_gap', 'session_id_inferred']].head(10))

Computing Session Duration

Session duration is the time between the first and last event in a session. Group by user_id and session_id and compute max - min on the timestamp column. Convert the resulting Timedelta to minutes with .dt.total_seconds() / 60 for a human-readable metric. Sessions with zero duration are single-event visits.

session_times = df.groupby(['user_id', 'session_id'])['timestamp'].agg(['min', 'max'])
session_times['duration_minutes'] = (session_times['max'] - session_times['min']).dt.total_seconds() / 60

print(session_times['duration_minutes'].describe())

Counting Events per Session

The number of events in a session is a proxy for user engagement. A session with 20 events likely indicates deeper exploration than one with 2. Use groupby(['user_id', 'session_id']).size() to count rows per group and name the result event_count. Merge this summary back to the sessions table for a complete session-level dataset.

event_counts = df.groupby(['user_id', 'session_id']).size().rename('event_count')
session_df = session_times.join(event_counts)

print(session_df.describe())

Identifying First and Last Events

The first event in a session shows the entry point (e.g. homepage vs. search results page) and the last event shows exit behaviour (purchase vs. bounce). Use groupby().first() and groupby().last() on the sorted DataFrame. These entry and exit columns are essential inputs for funnel and retention analysis.

session_entry = df.groupby(['user_id', 'session_id'])['event_type'].first().rename('entry_event')
session_exit = df.groupby(['user_id', 'session_id'])['event_type'].last().rename('exit_event')

print(session_entry.value_counts().head())
print(session_exit.value_counts().head())

Numbering Events Within a Session

Assigning a sequential event number within each session enables analysis of common event sequences. Use groupby(['user_id', 'session_id']).cumcount() + 1 to create an event_rank column. Filtering on event_rank == 1 gives the landing event; filtering on the maximum rank gives the exit event for each session.

df['event_rank'] = df.groupby(['user_id', 'session_id']).cumcount() + 1

# First event of each session
landings = df[df['event_rank'] == 1]
print(landings['event_type'].value_counts())

Computing Inter-Event Time

Inter-event time — the gap between consecutive events within a session — reveals how quickly users move through the product. Compute it with groupby(['user_id', 'session_id'])['timestamp'].diff(). Large gaps between specific event types suggest hesitation or confusion at that step, which is a signal for UX improvement.

df['inter_event_seconds'] = (
    df.groupby(['user_id', 'session_id'])['timestamp']
    .diff()
    .dt.total_seconds()
)

print(df['inter_event_seconds'].describe())

Session Count per User

The number of sessions per user measures how often each user returns. Power users with many sessions drive retention KPIs. Compute sessions per user with df.groupby('user_id')['session_id'].nunique(). Segment users into one-time visitors, occasional users, and frequent users using pd.qcut() on the session count.

sessions_per_user = df.groupby('user_id')['session_id'].nunique().rename('session_count')

print(sessions_per_user.describe())
print(sessions_per_user.value_counts().head(10))

Day-of-Week Session Distribution

Understanding which days of the week generate the most sessions helps schedule product releases, email campaigns, and server scaling. Extract day_of_week from the session start timestamp and group by it. Mapping integer values (0=Monday, 6=Sunday) to day names makes the output more readable in reports and charts.

session_starts = df[df['event_rank'] == 1].copy()
session_starts['day_of_week'] = session_starts['timestamp'].dt.day_name()

sessions_by_day = session_starts.groupby('day_of_week').size()
print(sessions_by_day)

Building a Session-Level Summary Table

Combine all computed metrics — duration, event count, entry event, exit event, and day of week — into a single session-level summary DataFrame. This table is the foundation for funnel analysis, retention modelling, and machine learning feature generation. Each row represents one session rather than one raw event.

session_summary = session_df.join(session_entry).join(session_exit)
session_summary = session_summary.reset_index()
print(session_summary.columns.tolist())
print(session_summary.head())

Quick Check

Test your understanding of Data Analysis concepts from this lesson.

Lesson Recap

In this lesson you learned: sorting events chronologically and inferring session boundaries from time gaps, computing session duration and event counts per session, and building a session-level summary table for downstream analysis. Next up we explore funnel analysis to measure conversion between product steps.

Frequently asked questions

Is the “Sessionisation and Event Sequencing” lesson free?

Yes — the full text of “Sessionisation and Event Sequencing” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Sessionisation and Event Sequencing”?

Group events by user and session, compute session duration with timestamp arithmetic, and sort events chronologically. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Sessionisation and Event Sequencing” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Sessionisation and Event Sequencing
  2. Funnel Analysis
  3. Cohort Retention Table
  4. Visualising User Journeys
← Back to Pandas & NumPy Academy