Sessionisierung und Ereignisabfolge
Gruppieren Sie Ereignisse nach Benutzer und Sitzung, berechnen Sie die Sitzungsdauer mithilfe von Zeitstempelarithmetik und sortieren Sie Ereignisse chronologisch.
Sessionisierung und Ereignisabfolge ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Sessionisierung und Ereignisabfolge“ kostenlos?
Ja — der vollständige Text von „Sessionisierung und Ereignisabfolge“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Sessionisierung und Ereignisabfolge“?
Gruppieren Sie Ereignisse nach Benutzer und Sitzung, berechnen Sie die Sitzungsdauer mithilfe von Zeitstempelarithmetik und sortieren Sie Ereignisse chronologisch. Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?
Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „Sessionisierung und Ereignisabfolge“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?
Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Sessionisierung und Ereignisabfolge
- Trichteranalyse
- Kohorten-Retention-Tabelle
- Nutzerreisen visualisieren