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

如何对MultiIndex多层索引DataFrame第一级索引执行类似group by操作

多层索引DataFrame按第一级索引分组实现方法

核心方法

pandas的groupby方法原生支持对MultiIndex按级别分组,直接通过level参数指定要分组的索引级别即可:

  • 按第一级索引的位置指定:groupby(level=0)
  • 按第一级索引的名称指定(可读性更高):groupby(level='month')

完整实现代码

首先导入依赖,生成你给出的初始MultiIndex DataFrame:

import pandas as pd

# 生成初始DataFrame
fruits=pd.DataFrame()
fruits['month']=['jan','feb','feb','march','jan','april','april','june','march','march','june','april']
fruits['fruit']=['apple','orange','pear','orange','apple','pear','cherry','pear','orange','cherry','apple','cherry']
fruits['price']=[30,20,40,25,30 ,45,60,45,25,55,37,60]

ind=(fruits.index)
fruits_grp = fruits.set_index(['month', ind],drop=False)

接下来按第一级索引分组,处理后得到目标结果:

res_list = []
# 按第一级索引month分组
for month, group in fruits_grp.groupby(level='month'):
    # 按需求替换月份缩写
    new_month = month.replace('april','apr').replace('june','jun')
    # 修改当前组的month字段值
    group['month'] = new_month
    # 重置组内索引,保证第二级索引是组内从0开始的序号
    group = group.reset_index(drop=True)
    res_list.append(group)

# 拼接所有组的结果
fruits_new = pd.concat(res_list, ignore_index=True)
# 按要求设置双层索引
fruits_grp1 = fruits_new.set_index(['month', fruits_new.index], drop=False)

结果验证

运行上述代码后输出fruits_grp1,和你给出的预期输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 06:30:05