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

Python旭日图:如何将层级Excel数据转换为嵌套列表格式

将Excel层级数据转换为旭日图所需嵌套列表格式

当然可以!咱们可以通过一段Python脚本,把你手里的Level0到Level3层级Excel数据,自动转换成旭日图函数要求的嵌套列表格式。下面是具体的实现步骤和代码:

1. 先整理你的Excel数据格式

你提供的Excel输出可以整理成更清晰的CSV格式(方便后续读取):

Level0,Level1,Level2,Level3,Volume
/,home,Images,,40
/,home,Videos,,20
/,home,Documents,,5
/,home,,,5
/,usr,src,linux-headers,4
/,usr,src,virtualbox,1
/,usr,src,,1
/,usr,lib,,4
/,usr,share,,2
/,usr,bin,,1
/,usr,local,,1
/,usr,include,,1

2. 编写转换脚本

我们会用pandas读取数据,然后递归构建嵌套结构,最后转换成目标格式:

import pandas as pd

def build_nested_structure(df):
    # 初始化根节点字典
    root = {'name': df.iloc[0]['Level0'], 'value': 0, 'children': []}
    
    # 遍历每一行数据
    for _, row in df.iterrows():
        levels = [row['Level0'], row['Level1'], row['Level2'], row['Level3']]
        volume = row['Volume']
        # 过滤空的层级名称(处理空字符串或NaN)
        valid_levels = [str(l) for l in levels if pd.notna(l) and str(l).strip() != '']
        
        # 从根节点开始逐层查找或创建子节点
        current_node = root
        for i, level_name in enumerate(valid_levels):
            # 检查当前节点的子节点中是否已有该层级名称
            child_exists = False
            for child in current_node['children']:
                if child['name'] == level_name:
                    current_node = child
                    child_exists = True
                    break
            # 如果不存在,创建新节点
            if not child_exists:
                new_node = {'name': level_name, 'value': 0, 'children': []}
                current_node['children'].append(new_node)
                current_node = new_node
        # 给最底层节点添加Volume值
        current_node['value'] += volume
    
    # 计算父节点的value(子节点value之和)
    def calculate_parent_values(node):
        if not node['children']:
            return node['value']
        total = node['value']
        for child in node['children']:
            total += calculate_parent_values(child)
        node['value'] = total
        return total
    
    calculate_parent_values(root)
    
    # 把字典格式转换成目标的元组嵌套列表格式
    def dict_to_tuple(node):
        children_tuples = [dict_to_tuple(child) for child in node['children']]
        return (node['name'], node['value'], children_tuples)
    
    return [dict_to_tuple(root)]

# 读取数据(如果是Excel文件,把pd.read_csv换成pd.read_excel('你的文件路径.xlsx'))
df = pd.read_csv('你的数据文件.csv')  # 替换成你的实际文件路径
data = build_nested_structure(df)

# 打印转换后的结果,和你给的示例格式完全一致
print(data)

3. 验证转换结果

运行上面的代码后,得到的data变量就完全符合旭日图函数的要求:

[ ('/', 100, [ ('home', 70, [ ('Images', 40, []), ('Videos', 20, []), ('Documents', 5, []), ]), ('usr', 15, [ ('src', 6, [ ('linux-headers', 4, []), ('virtualbox', 1, []), ]), ('lib', 4, []), ('share', 2, []), ('bin', 1, []), ('local', 1, []), ('include', 1, []), ]), ]), ]

直接调用sunburst(data)就能生成旭日图啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:49:20