I need to get a dataframe that shows me, in correspondence with the warehouse loads, when the stock would run out (excluding subsequent loads)
The starting dataframe is this: starting dataframe
Here you have the code to build it:
import pandas as pd
data = {'warehouse': ['M1', 'M1', 'M1', 'M1', 'M1', 'M1', 'M1', 'M1', 'M1', 'M2'],
'item': ['Partxy', 'Partxy', 'Partxy', 'Partxy', 'Partxy', 'Partxy', 'Partxy', 'Partxy', 'Partxy', 'Partz'],
'date': ['01/01/2023', '05/01/2023', '07/01/2023', '08/01/2023', '09/01/2023', '10/01/2023', '15/01/2023', '18/01/2023', '19/01/2023', '22/01/2023'],
'tot_load_replenishment': [0, 0, 20, 0, 0, 50, 0, 50, 0, 0],
'tot_unload': [0, -30, -15, -50, -10, -5, -30, -10, -5, -10],
'stock': [100, 70, 75, 25, 15, 60, 30, 70, 65, 300],
'stock_before_load': [None, None, 55, None, None, 10, None, 20, None, None]}
load_unload = pd.DataFrame(data)
load_unload['tot_load_replenishment'] = load_unload['tot_load_replenishment'].astype(int)
load_unload['tot_unload'] = load_unload['tot_unload'].astype(int)
load_unload['date'] = pd.to_datetime(load_unload['date'], format='%d/%m/%Y').dt.strftime('%Y-%m-%d')
What I want to obtain is this:
I tried this code:
#pass one item in one warehouse
item = 'Partxy'
warehouse = 'M1'
#filter the dataframe
item_war = (load_unload['item'] == item) & (load_unload['warehouse'] == warehouse)
load_unload_item_war = load_unload[item_war]
#consider only the row where I have some load for replenishment
mov_replenishment = load_unload_item_war[load_unload_item_war['tot_load_replenishment'] > 0]
#define a function that return the exhaustion_date, given the stock_before_load
def exhaustion_date(row, load_unload_item_war):
#consider only lines from today forward
f_load_unload_item_war = load_unload_item_war[(load_unload_item_war['date'] > row['date'])]
#store the stock before load in a specific variable
residual = row['stock_before_load']
#calculate the cumulative unloaded
f_load_unload_item_war['cum_unload'] = f_load_unload_item_war['tot_unload'].cumsum()*(-1)
#filter the dataframe to find the first date in which stock would become negative
exhaustion_date = f_load_unload_item_war.loc[f_load_unload_item_war['tot_unload'] < residual, 'date'].min()
return exhaustion_date
#apply the function to obtain the exaustion date only when I have a replenishment
mov_replenishment['exhaustion_date'] = mov_replenishment.apply(lambda row: exhaustion_date(row, load_unload_item_war), axis=1)
What I obtain is this (not correct):
Thanks in advance to anyone who can help me!