👥 05 · 用户画像与 RFM 分层¶
用户分层是精细化运营的入口。RFM = 最近购买 R + 频次 F + 金额 M,本节实现分层并画出价值矩阵。
📋 本节要解决的问题¶
| # | 问题 | 工具 |
|---|---|---|
| 1 | RFM 三个维度怎么定义? | 距今天数/次数/总金额 |
| 2 | 阈值怎么定? | 分位数 |
| 3 | 分层后怎么用? | 八宫格 / 运营动作 |
| 4 | 分层结果可视化 | 散点矩阵 |
Copied!
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'PingFang SC', 'Noto Sans CJK SC', 'Arial Unicode MS']
matplotlib.rcParams['axes.unicode_minus'] = False
import numpy as np
import pandas as pd
np.random.seed(42)
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'PingFang SC', 'Noto Sans CJK SC', 'Arial Unicode MS']
matplotlib.rcParams['axes.unicode_minus'] = False
import numpy as np
import pandas as pd
np.random.seed(42)
1️⃣ 构造用户交易数据¶
Copied!
rng = np.random.default_rng(21)
users = pd.DataFrame({
'user_id': range(1, 201),
'last_days': rng.exponential(30, 200).round(0), # 距最近购买天数
'freq': rng.integers(1, 30, 200), # 购买次数
'total': rng.uniform(50, 5000, 200).round(0), # 累计金额
})
print(users.head())
print('\n描述:')
print(users[['last_days', 'freq', 'total']].describe().round(1))
rng = np.random.default_rng(21)
users = pd.DataFrame({
'user_id': range(1, 201),
'last_days': rng.exponential(30, 200).round(0), # 距最近购买天数
'freq': rng.integers(1, 30, 200), # 购买次数
'total': rng.uniform(50, 5000, 200).round(0), # 累计金额
})
print(users.head())
print('\n描述:')
print(users[['last_days', 'freq', 'total']].describe().round(1))
user_id last_days freq total
0 1 8.0 26 2821.0
1 2 35.0 20 1029.0
2 3 138.0 6 4392.0
3 4 5.0 9 526.0
4 5 74.0 28 3876.0
描述:
last_days freq total
count 200.0 200.0 200.0
mean 29.7 15.1 2524.8
std 28.5 8.5 1371.8
min 0.0 1.0 53.0
25% 8.0 8.0 1390.5
50% 20.5 15.0 2494.5
75% 43.0 22.0 3619.5
max 149.0 29.0 4955.0
2️⃣ R/F/M 打分:按分位数二值化¶
✍️ §2.1 手算 RFM 打分:R=3 天 / F=5 次 / M=800 元 → 333 重要价值用户¶
RFM 三维打分:R 越近越好、F/M 越大越好——一个用户手算,看 3 个阈值判断。
设定:某用户最近购买距今 3 天、累计购买 5 次、累计消费 800 元。阈值:R ≤ 7 → 3 分;F ≥ 5 → 3 分;M ≥ 500 → 3 分。
| 维度 | 值 | 判断 | 得分 |
|---|---|---|---|
| R(最近一次购买距今) | 3 天 | ≤7 → 3 | 3 |
| F(购买频次) | 5 次 | ≥5 → 3 | 3 |
| M(消费金额) | 800 元 | ≥500 → 3 | 3 |
$$ ext{总分}=333\ \Rightarrow\ \text{重要价值用户(高价值高活跃)}$$
手算收获:
- RFM 把"用户价值"拆成三个可操作维度:R 监控流失风险、F 看粘性、M 看钱包份额——打分阈值通常用分位数(中位数二分,§2 代码)
- 八类分层的典型组合:333=重要价值(重点维护)、311=重要唤回(高消费但流失风险)、133=潜力用户(低消费高频)——组合语义要能脱口而出
- 阈值主观:业务不同分位点不同——打分规则先定分位点再看分数,否则分层失真
- 落地:分层 → 差异化运营(§5 建议表)——RFM 的价值在"分完类能行动"
下面 numpy 复算。
Copied!
# ---- §2.1 验证:numpy 复算 RFM 打分 ----
R, F, M = 3, 5, 800
r_score = 3 if R <= 7 else (2 if R <= 30 else 1)
f_score = 3 if F >= 5 else (2 if F >= 3 else 1)
m_score = 3 if M >= 500 else (2 if M >= 100 else 1)
score = r_score * 100 + f_score * 10 + m_score
print(f'RFM 分数 = ({r_score}, {f_score}, {m_score}) = {score}')
assert score == 333
print('\n✓ 与手算一致:重要价值用户')
# ---- §2.1 验证:numpy 复算 RFM 打分 ----
R, F, M = 3, 5, 800
r_score = 3 if R <= 7 else (2 if R <= 30 else 1)
f_score = 3 if F >= 5 else (2 if F >= 3 else 1)
m_score = 3 if M >= 500 else (2 if M >= 100 else 1)
score = r_score * 100 + f_score * 10 + m_score
print(f'RFM 分数 = ({r_score}, {f_score}, {m_score}) = {score}')
assert score == 333
print('\n✓ 与手算一致:重要价值用户')
RFM 分数 = (3, 3, 3) = 333 ✓ 与手算一致:重要价值用户
Copied!
# R:越近越好 → 小于中位数=1;F/M:越大越好 → 大于中位数=1
med_r = users['last_days'].median()
med_f = users['freq'].median()
med_m = users['total'].median()
users['R'] = (users['last_days'] <= med_r).astype(int)
users['F'] = (users['freq'] > med_f).astype(int)
users['M'] = (users['total'] > med_m).astype(int)
print(users[['user_id', 'R', 'F', 'M']].head())
print(f'中位数: R={med_r:.0f}天 F={med_f:.0f}次 M={med_m:.0f}元')
# R:越近越好 → 小于中位数=1;F/M:越大越好 → 大于中位数=1
med_r = users['last_days'].median()
med_f = users['freq'].median()
med_m = users['total'].median()
users['R'] = (users['last_days'] <= med_r).astype(int)
users['F'] = (users['freq'] > med_f).astype(int)
users['M'] = (users['total'] > med_m).astype(int)
print(users[['user_id', 'R', 'F', 'M']].head())
print(f'中位数: R={med_r:.0f}天 F={med_f:.0f}次 M={med_m:.0f}元')
user_id R F M 0 1 1 1 1 1 2 0 1 0 2 3 0 0 1 3 4 1 0 0 4 5 0 1 1 中位数: R=20天 F=15次 M=2494元
3️⃣ 用户分层(八类)¶
Copied!
def segment(r):
# apply(axis=1) 会把行转成 float,需显式 int() 再拼接
s = f'{int(r["R"])}{int(r["F"])}{int(r["M"])}'
mapping = {
'111': '重要价值用户', '110': '重要发展用户', '101': '重要保持用户', '100': '重要挽留用户',
'011': '一般价值用户', '010': '一般发展用户', '001': '一般保持用户', '000': '流失风险用户',
}
return mapping[s]
users['segment'] = users.apply(segment, axis=1)
print(users['segment'].value_counts())
assert '重要价值用户' in users['segment'].values
print('✅ 分层完成')
def segment(r):
# apply(axis=1) 会把行转成 float,需显式 int() 再拼接
s = f'{int(r["R"])}{int(r["F"])}{int(r["M"])}'
mapping = {
'111': '重要价值用户', '110': '重要发展用户', '101': '重要保持用户', '100': '重要挽留用户',
'011': '一般价值用户', '010': '一般发展用户', '001': '一般保持用户', '000': '流失风险用户',
}
return mapping[s]
users['segment'] = users.apply(segment, axis=1)
print(users['segment'].value_counts())
assert '重要价值用户' in users['segment'].values
print('✅ 分层完成')
segment 一般保持用户 33 重要发展用户 31 一般发展用户 26 重要保持用户 25 重要价值用户 22 重要挽留用户 22 流失风险用户 21 一般价值用户 20 Name: count, dtype: int64 ✅ 分层完成
4️⃣ 分层可视化:R×F 价值矩阵¶
Copied!
plt.figure(figsize=(7, 5))
sc = plt.scatter(users['R'] + rng.normal(0, 0.08, len(users)),
users['F'] + rng.normal(0, 0.08, len(users)),
c=users['M'], cmap='viridis', s=40, alpha=0.8)
plt.colorbar(sc, label='M(金额打分)')
plt.xticks([0, 1], ['R=0 久未购买', 'R=1 近期购买'])
plt.yticks([0, 1], ['F=0 低频', 'F=1 高频'])
plt.xlabel('R 最近购买')
plt.ylabel('F 购买频次')
plt.title('RFM 分层价值矩阵(颜色=金额)')
plt.show()
plt.figure(figsize=(7, 5))
sc = plt.scatter(users['R'] + rng.normal(0, 0.08, len(users)),
users['F'] + rng.normal(0, 0.08, len(users)),
c=users['M'], cmap='viridis', s=40, alpha=0.8)
plt.colorbar(sc, label='M(金额打分)')
plt.xticks([0, 1], ['R=0 久未购买', 'R=1 近期购买'])
plt.yticks([0, 1], ['F=0 低频', 'F=1 高频'])
plt.xlabel('R 最近购买')
plt.ylabel('F 购买频次')
plt.title('RFM 分层价值矩阵(颜色=金额)')
plt.show()
5️⃣ 分层运营建议¶
Copied!
suggestions = {
'重要价值用户': '重点维护,专属权益,防止流失',
'重要发展用户': '提高购买频次,交叉销售',
'重要保持用户': '唤醒召回,重新激活',
'重要挽留用户': '高价值但流失风险,紧急召回',
'一般价值用户': '常规触达,引导提频',
'一般发展用户': '培养消费习惯',
'一般保持用户': '低频但稳定,低成本维护',
'流失风险用户': '大促唤醒或放弃低效触达',
}
seg = users['segment'].mode()[0]
print(f'最大分层「{seg}」建议: {suggestions[seg]}')
print('\n各分层用户数:')
print(users['segment'].value_counts().sort_values(ascending=False))
suggestions = {
'重要价值用户': '重点维护,专属权益,防止流失',
'重要发展用户': '提高购买频次,交叉销售',
'重要保持用户': '唤醒召回,重新激活',
'重要挽留用户': '高价值但流失风险,紧急召回',
'一般价值用户': '常规触达,引导提频',
'一般发展用户': '培养消费习惯',
'一般保持用户': '低频但稳定,低成本维护',
'流失风险用户': '大促唤醒或放弃低效触达',
}
seg = users['segment'].mode()[0]
print(f'最大分层「{seg}」建议: {suggestions[seg]}')
print('\n各分层用户数:')
print(users['segment'].value_counts().sort_values(ascending=False))
最大分层「一般保持用户」建议: 低频但稳定,低成本维护 各分层用户数: segment 一般保持用户 33 重要发展用户 31 一般发展用户 26 重要保持用户 25 重要价值用户 22 重要挽留用户 22 流失风险用户 21 一般价值用户 20 Name: count, dtype: int64
📝 自测清单¶
- 能解释 RFM 三字母含义与打分规则
- 能用分位数设定阈值并说明其稳健性
- 能说出常见八分层的名字与运营动作
- 能指出 RFM 局限(不含新客、静态口径等)