Home > OS >  How to get balance value in a new column pandas
How to get balance value in a new column pandas

Time:09-30

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

CodePudding user response:

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
  • Related