I have following pandas dataframe
Code Sum Quantity
0 -12 0
1 23 0
2 -10 0
3 -12 0
4 100 0
5 102 201
6 34 0
7 -34 0
8 -23 0
9 100 0
10 100 0
11 102 300
12 -23 0
13 -25 0
14 100 123
15 167 167
My desired dataframe is
Code Sum Quantity new_sum
0 -12 0 -12
1 23 0 23
2 -10 0 -10
3 -12 0 -12
4 100 0 0
5 102 201 202
6 34 0 34
7 -34 0 -34
8 -23 0 -23
9 100 0 0
10 100 0 0
11 102 300 302
12 -23 0 -23
13 -25 0 -25
14 100 123 100
15 167 167 167
Logic is:
First I will check for non zero values in the quantity column. In the above sample data we got the first non zero occurance of quantity at index 4, which is 201. Then I want to add column sum till I get negative value in the row.
I have written a code, which uses nested if statements.However,it takes lot of time to execute the code because of multiple if's and row wise comparison.
current_stock = 0
for i in range(len(test)):
if(test['Quantity'][i] != 0):
current_stock = test['Sum'][i]
if(test['Sum'][i-1] > 0):
current_stock = current_stock + test['Sum'][i-1]
test['new_sum'][i-1] = 0
if(test['Sum'][i-2] > 0):
current_stock = current_stock + test['Sum'][i-2]
test['new_sum'][i-2] = 0
if(test['Sum'][i-3] > 0):
current_stock = current_stock + test['Sum'][i-3]
test['new_sum'][i-3] = 0
else:
test['new_sum'][i] = current_stock
else:
test['new_sum'][i] = current_stock
else:
test['new_sum'][i] = current_stock
else:
test['new_sum'][i] = test['Sum'][i]
Is there any better way to do it?
'stock_volume'but no such column exists. When you say "Then I want to add column sum till I get positive values in the row above index 4", what does that mean? If you add 100 to 0, you get 100 which is positive; not 202. Should they perhaps be greater than the value in'Quantity'? And in your code, it looks like you only check the 3 previous rows, but nothing about that appears in your logic.ifs, it's thefor.