How to get balance value in a new column pandas

Question:

here is my data frame

data={'first':[5,4,3,2,3], 'second':[1,2,3,4,5]}
df= pd.DataFrame(data)
        

first   second 
5        1      
4        2
3        3
2        4
3        5

and I want to do like this in third column like 0-5+1= -4, -4-4+2= -6, -6-3+3= -6, and so on. And I am sorry for I am not so good in English.

first   second third
 5       1      -4     #0-5(first)+1(second)= balance -4
 4       2      -6     #-4(balance)-4(first)+2(second)= balance -6
 3       3      -6
 2       4      -4
 3       5      -2
Asked By: Bashar

||

Answers:

You can subtract second from first and take the cumsum (cumulated sum):

df['third'] = (df['second']-df['first']).cumsum()

output:

   first  second  third
0      5       1     -4
1      4       2     -6
2      3       3     -6
3      2       4     -4
4      3       5     -2
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.