在Python的Pandas中进行分组和求和

在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
Python

输出

输入的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
Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册