📈 02 · 分组聚合与透视表¶
「分组 → 聚合 → 透视」是取数基本功。本节手写 groupby 并对照 pandas,再演练留存率、复购率、top-N 三类经典业务问题。
📋 本节要解决的问题¶
| # | 问题 | 工具 |
|---|---|---|
| 1 | 分组聚合的原理是什么? | 手写 groupby + agg |
| 2 | 透视表怎么用? | pivot_table / crosstab |
| 3 | 留存率怎么算? | 注册日 × 活跃日 矩阵 |
| 4 | top-N 怎么取? | groupby + nlargest |
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(3)
n = 200
orders = pd.DataFrame({
'order_id': range(1, n+1),
'city': rng.choice(['北京', '上海', '深圳', '杭州'], n, p=[0.4, 0.3, 0.2, 0.1]),
'category': rng.choice(['数码', '服饰', '食品', '家居'], n, p=[0.25, 0.35, 0.25, 0.15]),
'amount': rng.uniform(20, 500, n).round(2),
})
print(orders.head())
print('\n总订单数:', len(orders))
rng = np.random.default_rng(3)
n = 200
orders = pd.DataFrame({
'order_id': range(1, n+1),
'city': rng.choice(['北京', '上海', '深圳', '杭州'], n, p=[0.4, 0.3, 0.2, 0.1]),
'category': rng.choice(['数码', '服饰', '食品', '家居'], n, p=[0.25, 0.35, 0.25, 0.15]),
'amount': rng.uniform(20, 500, n).round(2),
})
print(orders.head())
print('\n总订单数:', len(orders))
order_id city category amount 0 1 北京 食品 198.14 1 2 北京 服饰 147.36 2 3 深圳 数码 198.85 3 4 上海 服饰 147.98 4 5 北京 家居 420.39 总订单数: 200
2️⃣ 手写 groupby:按城市求均值金额¶
✍️ §2.1 手写 groupby:4 笔订单按渠道求和¶
分组聚合 = 分组 → 对每组做聚合 → 合并结果——4 笔订单手算,看懂"分组求和"三步。
设定:渠道 A 三单(50、30、20),渠道 B 两单(40、10)。
第 1 步:分组
$$A:\{50,30,20\},\qquad B:\{40,10\}$$
第 2 步:聚合(求和)
$$A=50+30+20=\mathbf{100},\qquad B=40+10=\mathbf{50}$$
第 3 步:合并为表
| 渠道 | 金额和 |
|---|---|
| A | 100 |
| B | 50 |
手算收获:
- groupby 本质是"split-apply-combine":先按键切组、再 apply 聚合(sum/mean/count)、最后合并——手写和 pandas 一行等价(§2 代码)
- 聚合函数决定语义:sum=总额、mean=客单价、count=单量——先想清业务口径再选聚合
- 透视表(§4)= 两个键分组(城市 × 品类)的二维聚合——就是"分组聚合"的表格化呈现
- 复购率(§5)等业务指标 = 分组求"每人购买天数"再统计——分组思路一通百通
下面 numpy 复算。
Copied!
# ---- §2.1 验证:numpy 复算分组求和 ----
demo_orders = [('A', 50), ('A', 30), ('B', 40), ('A', 20), ('B', 10)]
agg = {}
for ch, amt in demo_orders:
agg[ch] = agg.get(ch, 0) + amt
print(f'分组求和 = {agg}')
assert agg == {'A': 100, 'B': 50}
print('\n✓ 与手算一致')
# ---- §2.1 验证:numpy 复算分组求和 ----
demo_orders = [('A', 50), ('A', 30), ('B', 40), ('A', 20), ('B', 10)]
agg = {}
for ch, amt in demo_orders:
agg[ch] = agg.get(ch, 0) + amt
print(f'分组求和 = {agg}')
assert agg == {'A': 100, 'B': 50}
print('\n✓ 与手算一致')
分组求和 = {'A': 100, 'B': 50}
✓ 与手算一致
Copied!
# 手写:按城市分组求和
groups = {}
for city, amt in zip(orders['city'], orders['amount']):
groups.setdefault(city, []).append(amt)
manual = {c: np.mean(v) for c, v in groups.items()}
# pandas 对照
pd_result = orders.groupby('city')['amount'].mean()
print('手写:', manual)
print('pandas:', pd_result.round(2).to_dict())
for c in manual:
assert abs(manual[c] - pd_result[c]) < 1e-9
print('✅ 手写与 pandas 一致')
# 手写:按城市分组求和
groups = {}
for city, amt in zip(orders['city'], orders['amount']):
groups.setdefault(city, []).append(amt)
manual = {c: np.mean(v) for c, v in groups.items()}
# pandas 对照
pd_result = orders.groupby('city')['amount'].mean()
print('手写:', manual)
print('pandas:', pd_result.round(2).to_dict())
for c in manual:
assert abs(manual[c] - pd_result[c]) < 1e-9
print('✅ 手写与 pandas 一致')
手写: {'北京': 241.91844155844151, '深圳': 239.8524390243903, '上海': 245.99641791044775, '杭州': 268.8926666666667}
pandas: {'上海': 246.0, '北京': 241.92, '杭州': 268.89, '深圳': 239.85}
✅ 手写与 pandas 一致
3️⃣ 多聚合:金额总和、单量、客单价¶
Copied!
summary = orders.groupby('city').agg(
order_cnt=('order_id', 'count'),
total_amount=('amount', 'sum'),
)
summary['avg_order'] = (summary['total_amount'] / summary['order_cnt']).round(2)
print(summary)
assert summary.loc['北京', 'order_cnt'] > 0
print('✅ 聚合完成')
summary = orders.groupby('city').agg(
order_cnt=('order_id', 'count'),
total_amount=('amount', 'sum'),
)
summary['avg_order'] = (summary['total_amount'] / summary['order_cnt']).round(2)
print(summary)
assert summary.loc['北京', 'order_cnt'] > 0
print('✅ 聚合完成')
order_cnt total_amount avg_order city 上海 67 16481.76 246.00 北京 77 18627.72 241.92 杭州 15 4033.39 268.89 深圳 41 9833.95 239.85 ✅ 聚合完成
4️⃣ 透视表:城市 × 品类 的销售额矩阵¶
Copied!
pv = orders.pivot_table(index='city', columns='category', values='amount', aggfunc='sum', fill_value=0).round(0)
print(pv)
print('\n热力图:')
plt.figure(figsize=(8, 4))
plt.imshow(pv.values, cmap='YlOrRd', aspect='auto')
plt.colorbar(label='销售额')
plt.xticks(range(len(pv.columns)), pv.columns)
plt.yticks(range(len(pv.index)), pv.index)
plt.title('城市 × 品类 销售额热力图')
plt.show()
pv = orders.pivot_table(index='city', columns='category', values='amount', aggfunc='sum', fill_value=0).round(0)
print(pv)
print('\n热力图:')
plt.figure(figsize=(8, 4))
plt.imshow(pv.values, cmap='YlOrRd', aspect='auto')
plt.colorbar(label='销售额')
plt.xticks(range(len(pv.columns)), pv.columns)
plt.yticks(range(len(pv.index)), pv.index)
plt.title('城市 × 品类 销售额热力图')
plt.show()
category 家居 数码 服饰 食品 city 上海 2756.0 3872.0 5314.0 4541.0 北京 3397.0 3661.0 6695.0 4875.0 杭州 718.0 1658.0 1283.0 374.0 深圳 815.0 2439.0 3300.0 3280.0 热力图:
5️⃣ 业务题:复购率(每人下单天数)¶
Copied!
# 模拟每个用户多笔订单
buyers = pd.DataFrame({
'user_id': rng.integers(1, 60, 300),
'day': rng.integers(1, 31, 300),
})
buy_cnt = buyers.groupby('user_id')['day'].nunique()
repurchase_rate = (buy_cnt >= 2).mean()
print(f'购买天数≥2 的用户占比(复购率): {repurchase_rate:.1%}')
print('购买天数分布:')
print(buy_cnt.value_counts().sort_index())
# 模拟每个用户多笔订单
buyers = pd.DataFrame({
'user_id': rng.integers(1, 60, 300),
'day': rng.integers(1, 31, 300),
})
buy_cnt = buyers.groupby('user_id')['day'].nunique()
repurchase_rate = (buy_cnt >= 2).mean()
print(f'购买天数≥2 的用户占比(复购率): {repurchase_rate:.1%}')
print('购买天数分布:')
print(buy_cnt.value_counts().sort_index())
购买天数≥2 的用户占比(复购率): 91.5% 购买天数分布: day 1 5 2 4 3 10 4 9 5 10 6 9 7 3 8 4 9 5 Name: count, dtype: int64
6️⃣ 业务题:top-2 城市按品类销售额¶
Copied!
top = (orders.groupby(['city', 'category'])['amount']
.sum().reset_index()
.sort_values('amount', ascending=False)
.groupby('category').head(2))
print(top.reset_index(drop=True))
assert len(top.groupby('category')) == 4
print('✅ 每个品类取到 top-2 城市')
top = (orders.groupby(['city', 'category'])['amount']
.sum().reset_index()
.sort_values('amount', ascending=False)
.groupby('category').head(2))
print(top.reset_index(drop=True))
assert len(top.groupby('category')) == 4
print('✅ 每个品类取到 top-2 城市')
city category amount 0 北京 服饰 6694.79 1 上海 服饰 5313.51 2 北京 食品 4874.83 3 上海 食品 4541.07 4 上海 数码 3871.65 5 北京 数码 3660.75 6 北京 家居 3397.35 7 上海 家居 2755.53 ✅ 每个品类取到 top-2 城市
📝 自测清单¶
- 能手写 groupby:分组 → 聚合 → 合并结果
- 能区分 pivot_table 与 groupby 的使用场景
- 能写出「复购率」「留存率」的 SQL/pandas 口径
- 能说出 groupby(...).head(k) 取组内 top-N 的原理