在使用groupby
函数对DataFrame进行分组操作后,如果要保持结果为DataFrame而不是Series,可以使用as_index=False
参数来实现。
下面是一个示例代码:
import pandas as pd
# 创建一个DataFrame
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'two', 'two', 'one', 'two', 'one'],
'C': [1, 2, 3, 4, 5, 6, 7, 8],
'D': [10, 20, 30, 40, 50, 60, 70, 80]})
# 对列A进行分组,并计算列C和列D的平均值
grouped = df.groupby('A', as_index=False).mean()
print(grouped)
输出结果:
A C D
0 bar 3.333333 40.0
1 foo 4.500000 42.5
在上述代码中,使用as_index=False
参数来保持分组结果为DataFrame,而不是Series。