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

如何在Pandas多层索引数据中添加聚合计算生成的新行?

让我一步步帮你搞定这两个多层索引DataFrame的扩展需求:

问题1:给which索引层添加max条目

首先先还原你给出的初始DataFrame:

import pandas as pd

df = pd.DataFrame({'panum': ['PA1', 'PA1', 'PA1', 'PA2', 'PA2', 'PA2'], 
                   'which': ['A', 'A', 'A', 'B', 'B', 'B'], 
                   'score': [88, 80, 90, 92, 95, 99]})
df.set_index(['panum', 'which'], inplace=True)

你的需求是给每个panum分组新增一行(panum, 'max'),对应该组score的最大值。实现步骤如下:

  1. 按panum分组计算每组的score最大值
  2. 给这些最大值行设置which为max,并还原成多层索引结构
  3. 把新生成的行和原DataFrame合并,最后排序索引保持结构一致

具体代码:

# 计算每个panum的score最大值,转换为带max标记的行
max_rows = df.groupby('panum')['score'].max().reset_index()
max_rows['which'] = 'max'
max_rows.set_index(['panum', 'which'], inplace=True)

# 合并并整理索引
df_with_max = pd.concat([df, max_rows]).sort_index()

最终df_with_max的结构会是:

score
panum which         
PA1   A          88
      A          80
      A          90
      max        90
PA2   B          92
      B          95
      B          99
      max        99

问题2:给panum索引层添加mean条目

先还原你提供的修正后DataFrame:

data = {'panum': ['PA1', 'PA1', 'PA1', 'PA2', 'PA2', 'PA2'],
        'factor': ['init', 'resub', 'final', 'init', 'resub', 'final'],
        'score': [90, 94, 93, 60, 90, 88]}
df2 = pd.DataFrame(data).set_index(['panum', 'factor'])

你的需求是新增panum为mean的条目,每个factor对应PA1和PA2的score均值。实现思路和第一个问题类似,只是分组维度换成了factor:

  1. 按factor分组计算每组的score均值(也就是PA1和PA2的平均值)
  2. 给这些均值行设置panum为mean,还原成多层索引
  3. 合并到原DataFrame并整理索引

具体代码:

# 计算每个factor的score均值,转换为带mean标记的行
mean_rows = df2.groupby('factor')['score'].mean().reset_index()
mean_rows['panum'] = 'mean'
mean_rows.set_index(['panum', 'factor'], inplace=True)

# 合并并整理索引
df2_with_mean = pd.concat([df2, mean_rows]).sort_index()

最终df2_with_mean的结构会是:

score
panum factor       
PA1   init      90.0
      resub     94.0
      final     93.0
PA2   init      60.0
      resub     90.0
      final     88.0
mean  init      75.0
      resub     92.0
      final     90.5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:20:24