jumpman8947
jumpman8947

Reputation: 437

python pandas dataframe add same row values

I have a dataframe which looks like this:

Fruit        Quantity
orange       4
grape        2
apple        3
grape        2
orange       1

I want to sum up the quantity column based off of the same item name in the fruit column. The desired result is :

Fruit      Quantity 
orange     5
apple      3
grape      4

Upvotes: 0

Views: 686

Answers (2)

tlentali
tlentali

Reputation: 3455

The answers from @GevorgAtanesyan and @d.b work perfectly.
However to get a DataFrame instead of a Serie as output, this notation can be used :

>>> df.groupby('Fruit')['Quantity'].sum().reset_index()
    Fruit   Quantity
0   apple   3
1   grape   4
2   orange  5

EDIT :
As suggested by @EmiOB, it is even tidier to write it like this :

>>> df.groupby('Fruit', as_index=False)['Quantity'].sum()
    Fruit   Quantity
0   apple   3
1   grape   4
2   orange  5

Upvotes: 3

Gevorg Atanesyan
Gevorg Atanesyan

Reputation: 49

Value counts is the best way

df.groupby('Fruit').sum()

Upvotes: 2

Related Questions