0

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
1
  • 4
    df.groupby("Fruit").sum() Commented Nov 1, 2021 at 22:33

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

or add as_index=False in the df.groupby bit, like so: df.groupby('Fruit', as_index=False).sum() Personally, I think it's a bit tidier
2

Value counts is the best way

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.