如何将带权重的边列表(Pandas DataFrame)导出为JSON树?
从Pandas DataFrame生成ECharts旭日图所需的JSON树结构
原始数据
给定如下Pandas DataFrame(实际包含200+行数据):
import pandas as pd df = pd.DataFrame({ 'child': ['Europe', 'France', 'Paris','North America', 'US', 'Canada'], 'parent': ["", 'Europe', 'France',"", 'North America', 'North America'], 'value': [746.4, 67.75, 2.16, 579,331.9, 38.25] })
DataFrame结构如下:
|---+---------------+---------------+--------| | | child | parent | value | |---+---------------+---------------+--------| | 0 | Europe | | 746.40 | | 1 | France | Europe | 67.75 | | 2 | Paris | France | 2.16 | | 3 | North America | | 579.00 | | 4 | US | North America | 331.90 | | 5 | Canada | North America | 38.25 | |---+---------------+---------------+--------|
目标结构
需要生成如下嵌套JSON树结构,作为ECharts旭日图的输入:
[ { name: 'Europe', value: 746.4, children: [ { name: 'France', value: 67.75, children: [ { name: 'Paris', value: 2.16 } ] } ] }, { name: 'North America', value: 579, children: [ { name: 'US', value: 331.9 }, { name: 'Canada', value: 38.25 } ] } ];
解决方案
通过递归遍历DataFrame构建层级字典,再转换为符合要求的JSON结构,代码实现如下:
import pandas as pd import json def build_tree(df): # 构建节点字典,快速定位节点 node_dict = {} for _, row in df.iterrows(): node_dict[row['child']] = { 'name': row['child'], 'value': row['value'], 'children': [] } # 组装树的层级关系 root_nodes = [] for _, row in df.iterrows(): parent_name = row['parent'].strip() child_node = node_dict[row['child']] if not parent_name: root_nodes.append(child_node) else: node_dict[parent_name]['children'].append(child_node) # 移除无子女节点的children字段,精简结构 def clean_empty_children(node): if not node['children']: del node['children'] else: for child in node['children']: clean_empty_children(child) for node in root_nodes: clean_empty_children(node) return root_nodes # 生成树结构并转为JSON tree_structure = build_tree(df) json_result = json.dumps(tree_structure, indent=4, ensure_ascii=False) print(json_result)
代码说明
- 节点字典初始化:遍历DataFrame,将每个子节点存入字典,后续可通过名称快速查找父/子节点。
- 层级组装:再次遍历DataFrame,根据parent字段将子节点挂载到对应父节点的children列表中,无父节点的直接作为根节点。
- 结构精简:递归清理没有子节点的children字段,让最终结构和示例一致。
- JSON转换:用
json.dumps将树结构转为JSON字符串,可直接用于ECharts的配置项。
内容的提问来源于stack exchange,提问作者crocefisso
相关产品推荐
相关产品推荐

