0Pricing
Pandas & NumPy Academy · 课时

会话划分与事件排序

按用户和会话对事件分组,使用时间戳运算计算会话时长,并按时间顺序排列事件。

会话划分与事件排序 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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.

常见问题解答

「会话划分与事件排序」课时是免费的吗?

是的 — 「会话划分与事件排序」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。

「会话划分与事件排序」这节课中我会学到什么?

按用户和会话对事件分组,使用时间戳运算计算会话时长,并按时间顺序排列事件。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Pandas & NumPy Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「会话划分与事件排序」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?

能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 会话划分与事件排序
  2. 漏斗分析
  3. 同期群留存表
  4. 可视化用户旅程
← 返回 Pandas & NumPy Academy