You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Python链接DataFrame转换为ECharts树形图所需层级字典

将父子关系DataFrame转换为ECharts树形图层级字典格式

实现思路

通过构建节点映射表,把DataFrame里的From-To父子关系转换成嵌套层级结构,最后给叶子节点补充value字段,完全匹配ECharts树形图所需的格式。

代码实现

import pandas as pd

def df_to_tree(df, root_name='Flare', default_value=3938):
    # 用字典存储所有节点,避免重复创建
    node_map = {}
    
    # 先初始化所有出现过的节点
    all_nodes = pd.concat([df['From'], df['To']]).unique()
    for node in all_nodes:
        node_map[node] = {'name': node}
    
    # 遍历每条父子关系,把子节点挂载到父节点的children列表中
    for _, row in df.iterrows():
        parent_node = node_map[row['From']]
        child_node = node_map[row['To']]
        
        # 父节点若无children列表则先初始化
        if 'children' not in parent_node:
            parent_node['children'] = []
        parent_node['children'].append(child_node)
    
    # 给无后代的叶子节点添加value字段
    for node in node_map.values():
        if 'children' not in node:
            node['value'] = default_value
    
    # 返回根节点的完整树形结构
    return node_map[root_name]

# 测试用示例DataFrame
sample_data = [
    ['Flare', 'Analytics'],
    ['Analytics', 'Cluster'],
    ['Cluster', 'AgglomerativeCluster'],
    ['Cluster', 'CommunityStructure'],
    ['Analytics', 'Graph'],
    ['Graph', 'CommunityStructure'],
    ['Graph', 'LinkDistance'],
    ['Flare', 'Data']
]
df = pd.DataFrame(sample_data, columns=['From', 'To'])

# 生成树形结构
tree_result = df_to_tree(df)
print(tree_result)

说明

  • 节点映射表node_map确保每个节点仅创建一次,避免重复实例化
  • 遍历DataFrame时直接通过映射表定位父子节点,快速构建嵌套关系
  • 叶子节点的value默认使用示例中的3938,你可根据需求修改default_value参数,或从其他数据源读取对应值
  • 若根节点不固定为Flare,可通过查找「仅出现在From列、未出现在To列」的节点自动定位根节点

内容的提问来源于stack exchange,提问作者SLE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:22:46