我如何 pandas 分组获得总和?

2022-01-29 00:00:00 python pandas dataframe group-by aggregate

问题描述

我正在使用这个数据框:

I am using this data frame:

Fruit   Date      Name  Number
Apples  10/6/2016 Bob    7
Apples  10/6/2016 Bob    8
Apples  10/6/2016 Mike   9
Apples  10/7/2016 Steve 10
Apples  10/7/2016 Bob    1
Oranges 10/7/2016 Bob    2
Oranges 10/6/2016 Tom   15
Oranges 10/6/2016 Mike  57
Oranges 10/6/2016 Bob   65
Oranges 10/7/2016 Tony   1
Grapes  10/7/2016 Bob    1
Grapes  10/7/2016 Tom   87
Grapes  10/7/2016 Bob   22
Grapes  10/7/2016 Bob   12
Grapes  10/7/2016 Tony  15

我想按 Name 然后按水果来汇总,以获得每个 NameFruit 总数.例如:

I want to aggregate this by Name and then by fruit to get a total number of Fruit per Name. For example:

Bob,Apples,16

我尝试按 NameFruit 进行分组,但如何获得 Fruit 的总数?

I tried grouping by Name and Fruit but how do I get the total number of Fruit?


解决方案

使用 GroupBy.sum:

df.groupby(['Fruit','Name']).sum()

Out[31]: 
               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

相关文章