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

如何修改Python Pandas代码实现指定嵌套Excel数据透视表?

如何生成嵌套层级带小计的数据透视表Excel文件?

看你的需求,是要生成一套带有Owner→Areas→Title→DNS嵌套层级,且每个层级都显示计数、最后带总计的Excel文件对吧?你原来的代码只用到了Areas作为透视表索引,自然出不来这种嵌套结构,咱们来一步步修改:

问题核心

你需要的不是单一维度的透视表,而是多级嵌套+各层级小计+总计的结构,这就需要我们按层级分组计算计数,再把各层级的结果整合起来。

修改后的完整代码

import pandas as pd

# 初始化数据(可替换为你的实际数据)
df = pd.DataFrame ({
    'Owner':['Brian','Andy','Paul'],
    'Areas':['BandA','Uat','Research'],
    'Title':['MS','Unix','Linux'],
    'DNS':['test','abc','production']
})

# 定义函数生成包含各层级小计的DataFrame
def add_subtotals(df, levels):
    dfs = []
    # 遍历每个层级,计算对应小计
    for i in range(len(levels)+1):
        if i == 0:
            # 计算总计
            total_count = df['Title'].count()
            subtotal_df = pd.DataFrame(
                {'Count_of_title': [total_count]},
                index=pd.MultiIndex.from_tuples([('Grand total',)], names=levels[:i])
            )
        else:
            # 计算当前层级的小计
            subtotal_df = df.groupby(levels[:i])['Title'].count().rename('Count_of_title').reset_index()
            # 为后续层级填充空值,方便排序后形成嵌套结构
            for col in levels[i:]:
                subtotal_df[col] = pd.NA
            subtotal_df = subtotal_df.set_index(levels)
        dfs.append(subtotal_df)
    
    # 合并所有层级数据并排序,让小计显示在子项上方
    combined_df = pd.concat(dfs).sort_index(na_position='first')
    # 把空值替换为空字符串,避免Excel显示NaN
    combined_df = combined_df.fillna('')
    return combined_df

# 指定嵌套层级的顺序
nested_levels = ['Owner', 'Areas', 'Title', 'DNS']
final_result = add_subtotals(df, nested_levels)

# 导出到Excel,保留索引以显示嵌套结构
with pd.ExcelWriter('out.xlsx', engine='openpyxl') as writer:
    final_result.to_excel(writer, index=True)

代码解释

  1. 层级小计生成:add_subtotals函数会依次遍历Owner→Areas→Title→DNS→总计这几个层级,分别计算每个层级的计数小计。
  2. 嵌套结构整理:通过填充空值+排序,让每个层级的小计和子项形成自然的嵌套缩进(Excel会自动识别多级索引的缩进)。
  3. 适配多数据场景:如果某个Owner对应多条数据(比如Brian在两个Area各有一套系统),对应的Owner小计、Area小计会自动累加,完全符合你描述的计数逻辑。

测试验证

比如你把初始数据改成:

df = pd.DataFrame ({
    'Owner':['Brian','Brian','Andy','Paul'],
    'Areas':['BandA','BandB','Uat','Research'],
    'Title':['MS','Windows','Unix','Linux'],
    'DNS':['test','prod','abc','production']
})

运行后会得到:

  • Brian的小计为2,BandA、BandB的小计各为1
  • 总计为4,完全符合你的预期逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:12:30