将任意深度嵌套字典树转换为Pandas DataFrame
问题:将嵌套层级不均的字典转换为Pandas DataFrame
需要将一个包含子节点列表的嵌套字典(节点深度和数量不均)转换为层级式的Pandas DataFrame,列数根据字典的最大深度自动生成。
示例字典
example_dict = { "id": 0, "children": [ {"id":4}, {"id": 1, "children":[{"id":2}, {"id":6}, {"id":7}, {"id":8}]}, {"id": 3, "children":[{"id":5}]}, {"id": 9, "children":[ {"id":10}, {"id": 11, "children":[{"id":12}, {"id":13}, {"id":14}, {"id":15}]} ]}, {"id": 16, "children":[ {"id":17}, {"id":18}, {"id":19}, {"id":20}, {"id": 21, "children":[ {"id":22}, {"id": 23, "children":[{"id":24}]} ]} ]} ] }
目标DataFrame结构
| Level 1 | Level 2 | Level 3 | Level 4 | Level 5 | |
|---|---|---|---|---|---|
| 0 | 0 | 4 | |||
| 1 | 0 | 1 | 2 | ||
| 2 | 0 | 1 | 6 | ||
| 3 | 0 | 1 | 7 | ||
| 4 | 0 | 1 | 8 | ||
| 5 | 0 | 3 | 5 | ||
| 6 | 0 | 9 | 10 | ||
| 7 | 0 | 9 | 11 | 12 | |
| 8 | 0 | 9 | 11 | 13 | |
| 9 | 0 | 9 | 11 | 14 | |
| 10 | 0 | 9 | 11 | 15 | |
| 11 | 0 | 16 | 17 | ||
| 12 | 0 | 16 | 18 | ||
| 13 | 0 | 16 | 19 | ||
| 14 | 0 | 16 | 20 | ||
| 15 | 0 | 16 | 21 | 22 | |
| 16 | 0 | 16 | 21 | 23 | 24 |
解决方案
核心思路是递归遍历嵌套字典的每个节点,记录每一条从根到叶子的路径,最后将所有路径整理成DataFrame,自动补全缺失的层级为NaN。
实现代码
import pandas as pd def traverse_tree(node, current_path, paths): # 将当前节点的id加入路径 current_path.append(node["id"]) # 如果当前节点没有子节点,保存这条路径 if "children" not in node or not node["children"]: paths.append(current_path.copy()) else: # 递归遍历每个子节点 for child in node["children"]: traverse_tree(child, current_path, paths) # 回溯,移除当前节点id,处理兄弟节点 current_path.pop() def dict_to_df(tree_dict): paths = [] # 从根节点开始遍历 traverse_tree(tree_dict, [], paths) # 找到最长路径的长度,确定列数 max_depth = max(len(path) for path in paths) # 生成列名 columns = [f"Level {i+1}" for i in range(max_depth)] # 将路径转换为DataFrame,缺失值补NaN df = pd.DataFrame(paths, columns=columns) return df # 测试转换 df = dict_to_df(example_dict) print(df)
代码说明
traverse_tree函数:递归遍历每个节点,维护当前路径,遇到叶子节点(无children或children为空)时保存路径,遍历完子节点后回溯路径,确保兄弟节点的路径正确。dict_to_df函数:初始化路径列表,调用遍历函数收集所有路径,根据最长路径生成对应层级的列名,最后将路径列表转为DataFrame,自动填充缺失层级为NaN。- 该方案支持任意深度的嵌套字典,列数会根据实际最大层级自动生成,适配600+节点的大规模数据。
内容的提问来源于stack exchange,提问作者A2er
相关产品推荐
相关产品推荐

