M6-005Mediumpandas 管道 · pandas pipelines

给定事件表(user_id, ts, event),如何用 pandas 计算每个用户的会话数(30 分钟规则)?

Given an events table (user_id, ts, event), compute sessions per user in pandas with a 30-minute rule.
💡 考场高分一句话答案:

排序 → groupby 求相邻时间差 → 标记新会话 → 累计求和 → 按用户数唯一会话 id。

Sort, take the within-user time difference, flag a new session when the gap exceeds 1800 seconds, cumulative-sum the flag, then count distinct sessions per user.

📌 核心考察要点 (Key Points)

  • 排序:必须按 user_id, ts 排序,否则 diff 无意义
  • 时间差:groupby('user_id')['ts'].diff().dt.total_seconds()
  • 累计:groupby('user_id')['is_new'].cumsum()
  • 边界:同一时间戳多事件需次级排序键
  • Sort first: by user_id and ts, otherwise diff is meaningless
  • Gap: groupby('user_id')['ts'].diff().dt.total_seconds()
  • Cumsum: groupby('user_id')['is_new'].cumsum() gives the session sequence
  • Edge case: identical timestamps need a secondary sort key

🔍 大厂面试官连环追问 (Follow-ups)

  • 如何计算“每用户日均会话数”?
  • 如果会话定义包含“无转化 30 分钟”,怎么改?

嫌字多看太累?进入苏格拉底式对话推演实验室

零打字负担,以大厂考官真实困境切入,通过点选直觉选项暴露思维盲区,手把手推导 Why。

💬 开启对话式破冰 ➔
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔