Reputation:
I have a df with name
,marks
and negative
. I'm trying to do a cumulative sum and subract negative
column.
df
name marks negative
0 marcus 20 0
1 marcus 30 10
2 marcus 0 20
3 paul 10 0
4 bruno 50 50
5 bruno 20 0
6 lucy 0 5
Final df
name marks negative finsum
0 marcus 20 0 20
1 marcus 30 10 40 (20+30-10) - (finsum+marks-negative)
2 marcus 0 20 20
3 paul 10 0 10
4 bruno 50 50 0
5 bruno 20 0 20
6 lucy 0 5 -5
I have tried cumsum()
for a single row, But how to add and subract with cumsum()
or is there any other way?
Upvotes: 0
Views: 31
Reputation: 862611
Use GroupBy.cumsum
:
df1 = df.groupby('name').cumsum()
df['fin'] = df1['marks'].sub(df1['negative'])
print (df)
name marks negative fin
0 marcus 20 0 20
1 marcus 30 10 40
2 marcus 0 20 20
3 paul 10 0 10
4 bruno 50 50 0
5 bruno 20 0 20
6 lucy 0 5 -5
Upvotes: 1