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 usesAandBas 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 columnsCandD.
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
相关产品推荐
相关产品推荐

