如何在Python中将嵌套字典转换为指定格式的DataFrame
实现代码
直接用以下代码就能完成需求:
import pandas as pd # 给定的嵌套字典 data = { "body-1": { "funtion-definition": ".c file", "funtion-definition-2": ".c file-2" }, "body-2": { "funtion-definition": ".c file", "funtion-definition-2": ".c file-2" } } # 把嵌套字典拆解成扁平行数据 rows = [] for group, func_info in data.items(): for func_name, file_name in func_info.items(): rows.append({ "Group": group, "function definition": func_name, ".c file": file_name }) # 创建DataFrame df = pd.DataFrame(rows) # 把同一分组的后续行Group列设为空字符串 df['Group'] = df['Group'].where(df['Group'] != df['Group'].shift(), '') # 输出格式匹配的表格 print(df.to_string(index=False))
运行后输出结果:
Group function definition .c file body-1 funtion-definition .c file funtion-definition-2 .c file-2 body-2 funtion-definition .c file funtion-definition-2 .c file-2
核心逻辑说明
- 先把嵌套字典逐层拆解成DataFrame需要的单行数据格式;
- 用
shift()对比当前行与上一行的Group值,重复值替换为空,实现分层显示效果; - 用
to_string(index=False)隐藏默认索引,让输出完全匹配需求样式。
内容的提问来源于stack exchange,提问作者Yash Mahale
相关产品推荐
相关产品推荐

