تقسيم الجلسات وتسلسل الأحداث
جمّع الأحداث حسب المستخدم والجلسة، واحسب مدة الجلسة باستخدام العمليات الحسابية على الطوابع الزمنية، ثم رتّب الأحداث زمنيًا.
تقسيم الجلسات وتسلسل الأحداث درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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.
الأسئلة الشائعة
هل درس «تقسيم الجلسات وتسلسل الأحداث» مجاني؟
نعم — نص درس «تقسيم الجلسات وتسلسل الأحداث» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
ماذا ستتعلم في «تقسيم الجلسات وتسلسل الأحداث»؟
جمّع الأحداث حسب المستخدم والجلسة، واحسب مدة الجلسة باستخدام العمليات الحسابية على الطوابع الزمنية، ثم رتّب الأحداث زمنيًا. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟
لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «تقسيم الجلسات وتسلسل الأحداث»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟
نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تقسيم الجلسات وتسلسل الأحداث
- تحليل المسار التحويلي
- جدول الاحتفاظ بالفوج
- تصور رحلات المستخدمين