本文介绍一种无需显式双重 for 循环的优雅方式,利用 pandas 的链式 groupby 和 apply 方法,将 dataframe 按多个列分组并转换为深度嵌套字典(如 {level1: {level2: [{record}, ...]}})。
在数据处理中,常需将扁平化的 DataFrame 转换为结构化嵌套字典,以适配 API 请求、配置生成或前端树形渲染等场景。传统双重 for 循环虽直观,但代码冗长、可读性差且难以扩展。更优解是充分利用 pandas 的分组聚合能力——通过嵌套 groupby().apply() 实现声明式层级构建。
核心思路是:外层按第一级键(如 'col1')分组 → 内层对每个子组再按第二级键(如 'col2')分组 → 对最内层子组调用 to_dict(orient='records') 生成记录列表。配合 .to_dict('index') 可自动将外层分组索引转为字典键。
以下为推荐实现(简洁、高效、可读性强):
import pandas as pd
# 构造示例数据
a = pd.DataFrame([
{'col1': 'A', 'col2': 'Person 1', 'height': 1, 'weight': 10},
{'col1': 'A', 'col2': 'Person 1', 'height': 2, 'weight': 20},
{'col1': 'A', 'col2': 'Person 1', 'height': 3, 'weight': 30},
{'col1': 'A', 'col2': 'Person 2', 'height': 4, 'weight': 40},
{'col1': 'A', 'col2': 'Person 2', 'height': 5, 'weight': 50},
{'col1': 'A', 'col2': 'Person 2', 'height': 6, 'weight': 60},
{'col1': 'B', 'col2': 'Person 1', 'height': 11, 'weight
': 101},
{'col1': 'B', 'col2': 'Person 1', 'height': 21, 'weight': 201},
{'col1': 'B', 'col2': 'Person 1', 'height': 31, 'weight': 301},
{'col1': 'B', 'col2': 'Person 2', 'height': 41, 'weight': 401},
{'col1': 'B', 'col2': 'Person 2', 'height': 51, 'weight': 501},
{'col1': 'B', 'col2': 'Person 2', 'height': 61, 'weight': 601},
])
# 一行式嵌套转换(推荐)
result = a.groupby('col1').apply(
lambda x: x.groupby('col2').apply(
lambda y: y.to_dict('records')
)
).to_dict('index')✅ 优势说明:
⚠️ 注意事项:
总结:通过 groupby().apply() 的嵌套组合,我们以函数式风格实现了清晰、健壮、可维护的多级嵌套字典转换——这是 pandas 高级用法的典型范例,值得纳入数据工程日常工具箱。