Pandas group-by and sum Pandas group-by and sum python python

Pandas group-by and sum


Use GroupBy.sum:

df.groupby(['Fruit','Name']).sum()Out[31]:                NumberFruit   Name         Apples  Bob        16        Mike        9        Steve      10Grapes  Bob        35        Tom        87        Tony       15Oranges Bob        67        Mike       57        Tom        15        Tony        1


Also you can use agg function,

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


If you want to keep the original columns Fruit and Name, use reset_index(). Otherwise Fruit and Name will become part of the index.

df.groupby(['Fruit','Name'])['Number'].sum().reset_index()Fruit   Name       NumberApples  Bob        16Apples  Mike        9Apples  Steve      10Grapes  Bob        35Grapes  Tom        87Grapes  Tony       15Oranges Bob        67Oranges Mike       57Oranges Tom        15Oranges Tony        1

As seen in the other answers:

df.groupby(['Fruit','Name'])['Number'].sum()               NumberFruit   Name         Apples  Bob        16        Mike        9        Steve      10Grapes  Bob        35        Tom        87        Tony       15Oranges Bob        67        Mike       57        Tom        15        Tony        1


matomo