如何计算用户的次日留存、7日留存?如何生成留存热力图?
进阶机器学习
答题要点
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# 假设数据:user_id, date (用户活跃日志)
df = pd.DataFrame(...)
df['date'] = pd.to_datetime(df['date'])
# 1. 确定每个用户的"首次活跃日期" (Cohort Date)
df['cohort_month'] = df.groupby('user_id')['date'].transform('min').dt.to_period('M')
# 2. 计算每次活跃距首活的月数 (Period Index)
df['current_month'] = df['date'].dt.to_period('M')
df['period_number'] = (df['current_month'] - df['cohort_month']).apply(lambda x: x.n)
# 3. 计算每个同期群在每个周期的活跃人数
cohort_data = df.groupby(['cohort_month', 'period_number'])['user_id'].nunique().reset_index()
# 4. 创建透视表 (行:首次月,列:第N个月,值:留存人数)
cohort_pivot = cohort_data.pivot(index='cohort_month', columns='period_number', values='user_id')
# 5. 计算留存率 (除以第0个月的人数)
cohort_size = cohort_pivot.iloc[:, 0] # 第0列是新增人数
retention = cohort_pivot.divide(cohort_size, axis=0)
# 6. 绘制热力图
plt.figure(figsize=(10, 8))
sns.heatmap(retention, annot=True, fmt='.1%', cmap='YlGnBu')
plt.title('Monthly Retention Rates')
plt.show()
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题