如何基于Pandas DataFrame构建递归JSON层级树?
从Pandas DataFrame构建多父节点JSON树
需求:基于给定的Pandas DataFrame生成JSON树结构,其中child_id列值为0的行作为根节点,其余节点通过id与父节点的child_id关联,形成层级结构。
原始数据
import pandas as pd data = { 'id': ['2', '13', '14', '15', '16', '17', '18'], 'name': ['color', 'red', 'blue', 'ruby red', 'mobile', 'iphone', 'sumsung'], 'child_id': ['0', '2', '2', '13', '0', '16', '16'] } df = pd.DataFrame(data)
解决方案代码
import json # 将id和child_id转为整数,避免字符串匹配问题 df['id'] = df['id'].astype(int) df['child_id'] = df['child_id'].astype(int) # 用字典存储所有节点,以id为键快速查找 node_dict = {} for _, row in df.iterrows(): node = row.to_dict() node['children'] = [] node_dict[row['id']] = node # 构建树形层级 tree = [] for node in node_dict.values(): parent_id = node['child_id'] if parent_id == 0: # child_id为0的是根节点,直接加入顶层列表 tree.append(node) else: # 非根节点找到对应父节点,加入父节点的children列表 node_dict[parent_id]['children'].append(node) # 转为格式化的JSON字符串 json_tree = json.dumps(tree, indent=2) print(json_tree)
代码说明
- 类型转换:把
id和child_id从字符串转为整数,确保匹配逻辑准确。 - 节点字典初始化:遍历DataFrame为每个节点创建字典,添加空的
children列表,用id作为键存入字典,方便后续快速定位父节点。 - 层级构建:遍历所有节点,根节点直接加入顶层;非根节点根据
child_id找到父节点,插入到父节点的子节点列表中。 - JSON输出:将最终树形结构转为格式化的JSON,与需求输出一致。
最终输出
[ { "name": "color", "id": 2, "child_id": 0, "children": [ { "name": "red", "id": 13, "child_id": 2, "children": [ { "name": "ruby red", "id": 15, "child_id": 13, "children": [] } ] }, { "name": "blue", "id": 14, "child_id": 2, "children": [] } ] }, { "name": "mobile", "id": 16, "child_id": 0, "children": [ { "name": "iphone", "id": 17, "child_id": 16, "children": [] }, { "name": "sumsung", "id": 18, "child_id": 16, "children": [] } ] } ]
注:如果不需要空的children字段,可以在构建完成后遍历节点删除空列表,或在初始化时按需处理。
内容的提问来源于stack exchange,提问作者T_Ner
相关产品推荐
相关产品推荐

