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

如何从pandas DataFrame生成适配d3.js动态树的带颜色属性JSON

实现方案

思路说明

  • 无需提前拆分Parent列为多列branch字段,直接逐行解析层级路径,通过字典缓存已创建的节点,避免重复构建层级,运行效率更高
  • 最终输出的JSON结构符合分类树要求:每个节点包含name字段,非叶子节点包含children数组字段,叶子节点额外携带color字段

完整实现代码

import pandas as pd
import json

# 1. 构造示例数据(实际使用时替换为读取你的源数据即可)
data = [
    ["IT;Programming;Trending;Demand", "Python", "#6200ea"],
    ["IT;Programming;Trending;Demand", "Docker", "#7c4dff"],
    ["IT;Programming;Testing", "Selenium", "#b388ff"],
    ["IT;Programming;Old", "C/C++/C#", "#ff1744"],
    ["IT-Tools;Testing", "HP UFT", "#aa00ff"],
    ["IT-Tools;IDE", "PyCharm", "#9c27b0"]
]
df = pd.DataFrame(data, columns=["Parent", "Child", "Color"])

# 2. 初始化树形结构根节点 + 路径缓存字典
root = {"name": "root", "children": []}
path_cache = {"root": root}

# 3. 逐行处理构建树形结构
for _, row in df.iterrows():
    # 拆分父层级路径,加上子节点构成完整层级链
    level_list = row["Parent"].split(";") + [row["Child"]]
    current_path = "root"
    current_node = root
    
    for idx, level_name in enumerate(level_list):
        current_path += f"|{level_name}"
        # 检查当前层级节点是否已创建
        if current_path not in path_cache:
            # 新建节点
            new_node = {"name": level_name}
            # 叶子节点(最后一级)添加color属性
            if idx == len(level_list) - 1:
                new_node["color"] = row["Color"]
            else:
                new_node["children"] = []
            # 加入父节点的children列表
            current_node["children"].append(new_node)
            # 缓存路径避免重复创建
            path_cache[current_path] = new_node
        # 切换到当前节点继续处理下一级
        current_node = path_cache[current_path]

# 4. 导出为JSON字符串
tree_json = json.dumps(root, ensure_ascii=False, indent=2)
print(tree_json)

# 如果需要导出到本地文件,执行下面代码即可
# with open("category_tree.json", "w", encoding="utf-8") as f:
#     json.dump(root, f, ensure_ascii=False, indent=2)

输出结构示例

{
  "name": "root",
  "children": [
    {
      "name": "IT",
      "children": [
        {
          "name": "Programming",
          "children": [
            {
              "name": "Trending",
              "children": [
                {
                  "name": "Demand",
                  "children": [
                    {
                      "name": "Python",
                      "color": "#6200ea"
                    },
                    {
                      "name": "Docker",
                      "color": "#7c4dff"
                    }
                  ]
                }
              ]
            },
            {
              "name": "Testing",
              "children": [
                {
                  "name": "Selenium",
                  "color": "#b388ff"
                }
              ]
            },
            {
              "name": "Old",
              "children": [
                {
                  "name": "C/C++/C#",
                  "color": "#ff1744"
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "name": "IT-Tools",
      "children": [
        {
          "name": "Testing",
          "children": [
            {
              "name": "HP UFT",
              "color": "#aa00ff"
            }
          ]
        },
        {
          "name": "IDE",
          "children": [
            {
              "name": "PyCharm",
              "color": "#9c27b0"
            }
          ]
        }
      ]
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 09:15:03