在Pandas中,可以使用groupby
方法按照某几列进行分组,并使用sum
方法求和。以下是一个代码示例:
import pandas as pd
# 创建示例DataFrame
data = {'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]}
df = pd.DataFrame(data)
# 按照'A'和'B'列进行分组,并对'C'和'D'列求和
grouped = df.groupby(['A', 'B']).sum()
print(grouped)
输出结果为:
C D
A B
bar one 2 80
two 4 40
foo one 9 100
two 10 100
在以上示例中,我们使用groupby(['A', 'B'])
将DataFrame按照'A'和'B'列进行分组,并使用sum()
对'C'和'D'列进行求和。最后,输出了分组并求和后的结果。