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

如何通过Python DataFrame的groupby生成指定结构的目标数据?

解决方法

你之前的groupby仅按id和type分组,遗漏了code字段,因此无法保留不同code维度的聚合结果,导致输出不符合预期。要得到目标结构,需要按id、type、code三个维度分组求和,再调整索引和列名:

分步实现代码

# 按id、type、code分组,对sum字段求和
df_new = df.groupby(['id', 'type', 'code'])['sum'].sum().reset_index()

# 设置多层索引并修改索引名称
df_new = df_new.set_index(['id', 'type']).rename_axis(index={'id': 'code', 'type': 'id'})

# 修改列名匹配目标结构
df_new = df_new.rename(columns={'code': 'type'})

链式简洁写法

df_new = (df.groupby(['id', 'type', 'code'])['sum'].sum()
          .reset_index()
          .set_index(['id', 'type'])
          .rename_axis(index={'id': 'code', 'type': 'id'})
          .rename(columns={'code': 'type'}))

最终输出

运行后得到的结果与你期望的结构完全一致:

type  sum
code id            
AAA  1    abc    5
     1    reg    5
     1    ses    5
BBB  1    ses    3
     2    abc    3
     2    reg    2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:35:14