I am looking to build a function that creates a rolling total by code by day for the below DataFrames, where the In for each code on a date is subtracted from the Out for each code on a date, this subtotal is the subtracted from the previous days total but the total must be >=0 ( I have included an example of this it the Desired Output below).
Below are an example of my inputs and the function I am using along with an example of my desired output.
df1 - In
s = """ Date Code Quantity
0 10/01/2019 A 20
3 11/01/2019 A 2
7 12/01/2019 A 4
11 13/01/2019 A 10
"""
df2 - Out
s =''' Date Code Quantity
0 11/01/2019 A 5
3 12/01/2019 A 100
4 15/01/2019 A 1
6 16/01/2019 A 2
'''
Code
df3 = df1.merge(df2, how='outer', left_on=['date', 'code'], right_on=['date', 'code']).fillna(0)
df3['qty1'] = df3['qty_x'] - df3['qty_y']
df3['qty'] = 0
def final_adder(x):
x.qty_x = x.qty_x
print(x)
return x
df_final = df3.groupby(['code']).apply(final_adder)
df_final['qty'] = df_final['qty'].clip(lower=0)
df_final.drop(['qty_x', 'qty_y','qty1'], inplace=True, axis=1)
date code qty_x qty_y qty1 qty
0 10/01/2019 A 20.0 0.0 20.0 0
3 11/01/2019 A 2.0 5.0 -3.0 0
7 12/01/2019 A 4.0 100.0 -96.0 0
11 13/01/2019 A 10.0 0.0 10.0 0
Desired Output
s = """ Date Code Quantity
0 10/01/2019 A 20
3 11/01/2019 A 17
7 12/01/2019 A 0
11 13/01/2019 A 10
12 14/01/2019 A 10
15 15/01/2019 A 9
16 16/01/2019 A 7
"""