Home > Net >  python pandas dataframe add same row values
python pandas dataframe add same row values

Time:11-02

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

CodePudding user response:

Value counts is the best way

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

CodePudding user response:

The answers from @GevorgAtanesyan and @d.b work perfectly ( 1).
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
  • Related