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

pandas MultiIndex DataFrame多级列求和 计算one/two列总计值

pandas MultiIndex多层列DataFrame求和添加总计行方法

针对多层列DataFrame计算二级标签为one、two的列总和、并追加Total总计行的需求,可按以下方式实现,全程保留原有多层列结构:

核心实现逻辑

  • 多层列可以通过get_level_values按层级筛选目标列,适配后续二级标签新增其他值的扩展场景
  • 沿行方向(axis=0)计算目标列的求和值,生成为单行DataFrame
  • 通过拼接操作将总计行追加到原表末尾,不会破坏原有的多层索引结构

完整可运行代码

import pandas as pd

# 1. 构造和示例一致的多层列DataFrame
columns = pd.MultiIndex.from_product(
    [['bar', 'baz', 'foo'], ['one', 'two']],
    names=['first', 'second']
)
df = pd.DataFrame(
    [
        [0.895717, 0.805244, 1.206412, 2.565646, 1.431256, 1.431256],
        [0.410835, 0.813850, 0.132003, 0.827317, 0.076467, 0.076467],
        [1.413681, 1.607920, 1.024180, 0.569605, 0.875906, 0.875906]
    ],
    index=['A', 'B', 'C'],
    columns=columns
)

# 2. 筛选二级层级为one、two的目标列,计算列总和
target_col_mask = df.columns.get_level_values('second').isin(['one', 'two'])
total_row = df.loc[:, target_col_mask].sum(axis=0).to_frame().T
total_row.index = ['Total']

# 3. 拼接总计行到原表
df_result = pd.concat([df, total_row])

运行结果

执行代码后得到的结果和预期结构完全一致,Total行各单元格为对应列的求和值:

first        bar                 baz                 foo          
second       one       two       one       two       one       two
A       0.895717  0.805244  1.206412  2.565646  1.431256  1.431256
B       0.410835  0.813850  0.132003  0.827317  0.076467  0.076467
C       1.413681  1.607920  1.024180  0.569605  0.875906  0.875906
Total   2.720233  3.227014  2.362595  3.962568  2.383629  2.383629

注:如果你的多层列里二级标签只有one、two两类,可以省略列筛选步骤,直接用df.sum(axis=0)计算全列和即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:54:15