M6-007Mediumpandas 管道 · pandas pipelines🔥 大厂高频出现 1 次
如何用 pandas 计算留存矩阵(cohort × day_n)?
Compute a retention matrix (cohort × day_n) in pandas.
💡 考场高分一句话答案:
求每个用户首次活跃日作 cohort,与活跃日做差得 day_n,再 pivot_table 计数并按 cohort 规模归一。
Take each user's first active date as the cohort, subtract it from each active date to get day_n, pivot with nunique, then divide by the cohort's day-0 size.
🧭 Playbook 核心提示 / Actionable Calibration:
注意 nunique 而不是 count:同一天多次活跃要去重。另外新 cohort 在长 day_n 上应为 NaN(右删失),不要 fillna(0),否则曲线假性下跌。
📌 核心考察要点 (Key Points)
- cohort:groupby('user_id')['dt'].transform('min')
- day_n:(dt - cohort).dt.days
- 透视:pivot_table(index='cohort', columns='day_n', values='user_id', aggfunc='nunique')
- 归一:除以 day_0 的人数得到留存率
- Cohort: groupby('user_id')['dt'].transform('min')
- day_n: (dt - cohort).dt.days
- Pivot: pivot_table(index='cohort', columns='day_n', values='user_id', aggfunc='nunique')
- Right censoring: recent cohorts have NaN for long day_n; do not fill with zero or the curve dips falsely
🔍 大厂面试官连环追问 (Follow-ups)
- 如何只保留规模 ≥ 1000 的 cohort?
- 如何画留存曲线(按 cohort 平均)?
🎯 关联大厂考题实战训练 (1 题)
嫌字多看太累?进入苏格拉底式对话推演实验室
零打字负担,以大厂考官真实困境切入,通过点选直觉选项暴露思维盲区,手把手推导 Why。
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.