在Python的Pandas中进行分组和求和
要在Python的Pandas中进行分组和求和,我们可以使用 groupby(columns).sum() 。
步骤
- 创建一个二维的、大小可变的、可能是异构的表格数据, df 。
- 打印输入的数据框, df 。
- 使用 df.groupby().sum() 来找到分组和求和。这个函数接受给定的列并对其值进行排序。之后,基于排序后的值,它还会对其他列的值进行排序。
- 打印分组和。
示例
import pandas as pd
df = pd.DataFrame(
{
"Apple": [5, 2, 7, 0],
"Banana": [4, 7, 5, 1],
"Carrot": [9, 3, 5, 1]
}
)
print "输入的DataFrame 1为:\n", df
g_sum = df.groupby(['Apple']).sum()
print "按Apple分组为:\n", g_sum
输出
输入的DataFrame 1为:
Apple Banana Carrot
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1
按Apple分组为:
Apple Banana Carrot
0 1 1
2 7 3
5 4 9
7 5 5