how to do the sum of values in a dataframe column with recurring indices

Viewed 103

i need a little bit of help with this unique problem. i have the following dataframe:

              volume
index
 1              5
 1             10
 1             10
 2              6
 2              8
 2              5
 3             15
 3              5

i want to create a new dataframe that adds all the values in the respective indices (for index 1, add 5+10+10= 25 , etc) as shown below: how do i go about it?

          volume
 index
  1        25
  2        19
  3        20
2 Answers

As a pandas newbie, I am still struggling with just making my dataframe look like the data presented in the question. I settled for this approach:

import pandas as pd
df = pd.DataFrame(
  { "volume" : [ 5,10,10,6,8,5,15,5 ]}, index=[1,1,1,2,2,2,3,3]  )

print(df.groupby(level=0).sum())

To yield this dataframe:

   volume
1       5
1      10
1      10
2       6
2       8
2       5
3      15
3       5

And this result:

   volume
1      25
2      19
3      20
Related