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

Pandas多列GroupBy后如何获取整数形式的普通索引?

How to Get a Regular Integer Index After GroupBy in Pandas

The issue you're facing is that groupby uses your grouping columns (A and B) as a multi-index in the result. To switch to a standard integer index, you can use the reset_index() method with the drop=True parameter—this will discard the multi-index and replace it with pandas' default integer-based index.

Here's the modified code that produces your desired output:

import pandas as pd
import numpy as np
from pandas import Series

df = pd.DataFrame({'A': [1, 1, 2, 2], 'B': [1, 2, 2, 2], 'C': np.random.randn(4), 'D': ['one', 'two', 'three', 'four']})

def aggregate(x):
    return Series(dict(C=round(x['C'].mean()), D=' '.join(x['D'])))

# Generate grouped result and reset index to integer
result = df.groupby(['A', 'B']).apply(aggregate).reset_index(drop=True)
print(result)

How it works:

  • The original groupby().apply() output uses A and B as a hierarchical (multi-level) index to represent the groups.
  • reset_index(drop=True) removes this multi-index entirely and replaces it with a sequential integer index (0, 1, 2...), while preserving your aggregated columns C and D.

If you ever wanted to keep A and B as regular columns (not index), you could omit the drop=True parameter—this would convert the multi-index into columns and add the integer index alongside them.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:43:58