Home > Blockchain >  Pandas: Generate column on group by and cumsum
Pandas: Generate column on group by and cumsum

Time:12-13

The task is to generate a column cur where cur = cur pts until id contains same consecutive value. It will continue iteratively. NB: Initially cur contains 0 by default

Sample dataframe:

   id pts
0   1   1
1   1   2
2   1   1
3   2   9
4   2   0
5   3   0
6   3   1
7   3   4

Expected output:

   id pts cur
0   1   1   1
1   1   2   3
2   1   1   4
3   2   9   9
4   2   0   9
5   3   0   0
6   3   1   1
7   3   4   5

My code:

gr = df.groupby(["id"]).cumsum()
df["cur"] = gr.pts.cumsum()

CodePudding user response:

Wouldn't this work?

df['cur'] = df.groupby('id')['pts'].cumsum()

   id  pts  cur
0   1    1    1
1   1    2    3
2   1    1    4
3   2    9    9
4   2    0    9
5   3    0    0
6   3    1    1
7   3    4    5
  • Related