Python Pandas 中的分组和求和
pythonserver side programmingprogramming更新于 2025/10/27 15:08:17
要在 Python Pandas 中查找分组和求和,我们可以使用 groupby(columns).sum()。
步骤
- 创建一个二维、大小可变、可能异构的表格数据 df。
- 打印输入 DataFrame,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 "Input DataFrame 1 is:\n", df
g_sum = df.groupby(['Apple']).sum()
print "Group by Apple is:\n", g_sum
输出
Input DataFrame 1 is: Apple Banana Carrot 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Group by Apple is: Apple Banana Carrot 0 1 1 2 7 3 5 4 9 7 5 5
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

