0

My dataframe looks like this:

Products         Value
Product A        10
Product B        12
Product C        8
Product A        5
Product A        8

This is what im trying to do:

Products         Value
Product A        23
Product B        12
Product C        8

Is there an easy way to do this? Thanks

JvdV
  • 70,606
  • 8
  • 39
  • 70
M.Buetzer
  • 13
  • 2
  • 1
    Does this answer your question? [Pandas group-by and sum](https://stackoverflow.com/questions/39922986/pandas-group-by-and-sum). Or [this](https://stackoverflow.com/q/28236305/9758194) – JvdV Feb 28 '20 at 08:29
  • This is definitely a duplicate. Links provided by @JvdV should cover your requirements. – moys Feb 28 '20 at 08:32
  • @moys - I not agree, else closed, because grouping by `index`, so cannot be used `df.sum(level=0)` in answer of dupe – jezrael Feb 28 '20 at 08:34
  • df1 = df.groupby('Products').sum() this worked thx – M.Buetzer Feb 28 '20 at 08:41
  • @jezrael `df.groupby('Products').sum()` meets the needs of the OP. `df.sum(level=0)` is a good alternative that can be added to the dupe so that all options are in one place. Just a suggestion. – moys Feb 28 '20 at 08:41
  • @moys - yes, unfortunately only in pandas 0.23+ (because `Product` is index, not column) – jezrael Feb 28 '20 at 08:42
  • @moys - cannot add to dupe, because in dupe is grouping by column, not by index. – jezrael Feb 28 '20 at 08:43
  • @moys - Part dupe is [this](https://stackoverflow.com/a/53404689/2901002), but without `set_index` cannot be used. – jezrael Feb 28 '20 at 08:44
  • @jezrael No problem. I expressed what I felt. Sorry if it offended you. – moys Feb 28 '20 at 08:46
  • @moys - I only explain why not close, but add answer ;) – jezrael Feb 28 '20 at 08:46

2 Answers2

2

Use DataFrame.sum by level:

df1 = df.sum(level=0)
print (df1)
           Value
Products         
Product A     23
Product B     12
Product C      8

Another solution with DataFrame.groupby working in newer pandas solution too, if index has name Products:

df1 = df.groupby('Products').sum()
print (df1)
           Value
Products        
Product A     23
Product B     12
Product C      8
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

Yes, take a look at groupby

df.groupby("Products")["Value"].sum() 
Manny
  • 85
  • 8