Python Pandas 中的 group-by 和 sum
若要在 Python Pandas 中查找 group-by 和 sum,我们可以使用 groupby(columns).sum()。
步骤
- 创建一个二维、大小可变、可能非同质的表格数据 df。
- 打印输入 DataFrame df。
- 使用 df.groupby().sum() 查找 groupby sum。此函数使用给定的列并对该列的值进行排序。然后,根据排序的值,也会对其他列的值进行排序。
- 打印 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP