Sessões e sequência de eventos
Agrupe eventos por usuário e sessão, calcule a duração da sessão com operações aritméticas sobre marcas de tempo e ordene os eventos cronologicamente.
Sessões e sequência de eventos é uma aula grátis de Pandas & NumPy Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Pandas & NumPy Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Pandas & NumPy Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Perguntas Frequentes
A aula “Sessões e sequência de eventos” é grátis?
Sim — o texto completo de “Sessões e sequência de eventos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Pandas & NumPy Academy, atualize para CoddyKit PRO. O curso de Pandas & NumPy Academy inclui 4 aulas no total.
O que vou aprender em “Sessões e sequência de eventos”?
Agrupe eventos por usuário e sessão, calcule a duração da sessão com operações aritméticas sobre marcas de tempo e ordene os eventos cronologicamente. Você pratica Pandas & NumPy Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Pandas & NumPy Academy?
Nenhuma experiência prévia é necessária. Pandas & NumPy Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Sessões e sequência de eventos”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Pandas & NumPy Academy?
Sim. Cada aula de Pandas & NumPy Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Sessões e sequência de eventos
- Análise de funil
- Tabela de retenção por coorte
- Visualizando jornadas de usuários