So I have this data frame and function code:
df = pd.DataFrame({'SUPPLIER': ['SUP1', 'SUP1', 'SUP1', 'SUP2', 'SUP2', 'SUP2'],
'PRODUCTID': ['P1', 'P1', 'P1', 'P4', 'P4', 'P4'],
'STOREID': ['STR1', 'STR2', 'STR3', 'STR1', 'STR2', 'STR3'],
'BALANCE': [50, 6, 74, 35, 5, 54],
'AVG_SALES': [5, 4, 4, 3, 4, 7],
'TO_SHIP': [18, 18, 18, 500, 500, 500],
'EXTRA_SHIP': [2, 2, 2, 3, 3, 3],})
def find_min(x):
num_mins = x["Wk_bal"].loc[x["Wk_bal"] == x["Wk_bal"].min()].shape[0]
if num_mins == 1:
return(x["Wk_bal"].idxmin())
else:
min_df = x.loc[x["Wk_bal"] == x["Wk_bal"].min()]
return(min_df["AVG_SALES"].idxmax())
I have a while loop below that distributes shipments (TO_SHIP) to the stores with the lowest weeks of supply. The code works well. I'm trying to add another while loop or if else inside the while statement to distribute the EXTRA_SHIP. But it's not working for me.
Here's the code without extra shipment which works just to allocate / send the packages from the TO_SHIP.
df['SEND_PKGS'] = 0
df['SEND_EXTRA_PKGS'] = 0
df['Wk_bal'] = (df['BALANCE']+1) / df['AVG_SALES']
while (df['TO_SHIP'] != 0).any():
lowest_idx = df[df['TO_SHIP'] > 0].groupby(["SUPPLIER", "PRODUCTID"])[['Wk_bal', 'AVG_SALES']].apply(find_min)
df.loc[lowest_idx, 'SEND_PKGS'] += 1
df['Wk_bal'] = ((df['BALANCE']+1) + df['SEND_PKGS']) / df['AVG_SALES']
df.loc[df['TO_SHIP'] > 0, 'TO_SHIP'] -= 1
Here's the code where I'm trying to create a nested while loop to allocate extra shipment based on similar conditions while extra shipment > 0. It doesn't seem to work for me.
while (df['TO_SHIP'] != 0).any():
lowest_idx = df[df['TO_SHIP'] > 0].groupby(["SUPPLIER", "PRODUCTID"])[['Wk_bal', 'AVG_SALES']].apply(find_min)
df.loc[lowest_idx, 'SEND_PKGS'] += 1
while (df['EXTRA_SHIP'] != 0).any():
df.loc[lowest_idx, 'SEND_EXTRA_PKGS'] += 1
df.loc[df['EXTRA_SHIP'] > 0, 'EXTRA_SHIP'] -= 1
df['Wk_bal'] = ((df['BALANCE']+1) + df['SEND_PKGS']) / df['AVG_SALES']
df.loc[df['TO_SHIP'] > 0, 'TO_SHIP'] -= 1
How can I fix this so that I can have an output with Send pkgs and Send extra pkgs?