Home > Software design >  How to sum values in group for each value in other column?
How to sum values in group for each value in other column?

Time:11-30

I have a dataframe:

id   life_day   value
a1     1         10
a1     2         20
a1     3         10
a1     4         5
a1     5         5
a1     6         1
b2     1         7
b2     3         11
b2     4         10
b2     5         20

I want to sum values for each id and life_day. So desired result is:

id   life_day   value
a1     1         10
a1     2         30
a1     3         40
a1     4         45
a1     5         50
a1     6         51
b2     1         7
b2     3         18
b2     4         28
b2     5         48

`

How to do that? I tried df.groupby('id').agg({'value': 'sum'}) but brings wrong results. It doesnt do summing.

CodePudding user response:

try, transform cumsum

df['value'] = df.groupby(['id'])['value'].transform('cumsum')

   id  life_day  value
0  a1         1     10
1  a1         2     30
2  a1         3     40
3  a1         4     45
4  a1         5     50
5  a1         6     51
6  b2         1      7
7  b2         3     18
8  b2         4     28
9  b2         5     48
  • Related