Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Cumsum Reset based on a condition in Pandas

My question is very similar to Cumsum within group and reset on condition in pandas and Pandas: cumsum per category based on additional condition but they don't quite get me there due to my conditional requirements. I have a data frame that looks like this:

  TransactionId     Delta
          14          2
          14          3
          14          1
          14          2
          15          4
          15          2
          15          3

I want to create another column "Cumulative" that calculates the cumsum of Delta for each TransactionId. So the result would look like this:

  TransactionId     Delta    Cumulative
          14          2          2
          14          3          5
          14          1          6
          14          2          8
          15          4          4
          15          2          6
          15          3          9

I have the condition for checking TransactionId equality setup:

c1 = df.TransactionId.eq(df.TransactionId.shift())

But I can't figure out how to add the Delta value to the previous Cumulative row.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use groupby.cumsum:

df['Cumulative'] = df.groupby('TransactionId')['Delta'].cumsum()

print (df)

  TransactionId  Delta  Cumulative
0       14         2       2
1       14         3       5
2       14         1       6
3       14         2       8
4       15         4       4 
5       15         2       6 
6       15         3       9

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...