I have two dataframes: one containing replenishment orders for some products, and one containing sales data for the same products by month over multiple years. I have only included the entries for one specific product here. I have already used groupby to calculate the average sales per month per product from the sales data (grouper):
grouper = sales.groupby(['Country Code', 'Product', 'Product Description', 'Month'])['Sales Quantity [QTY]'].mean()
Returns:
index Country Code Product Product Description Month Sales Quantity [QTY]
1 Belgium BE3194 GEL DOUCHE 500ML 1 3.000000
2 Belgium BE3194 GEL DOUCHE 500ML 2 1.750000
3 Belgium BE3194 GEL DOUCHE 500ML 3 2.333333
4 Belgium BE3194 GEL DOUCHE 500ML 4 2.000000
5 Belgium BE3194 GEL DOUCHE 500ML 5 2.000000
6 Belgium BE3194 GEL DOUCHE 500ML 6 1.500000
7 Belgium BE3194 GEL DOUCHE 500ML 7 5.000000
8 Belgium BE3194 GEL DOUCHE 500ML 8 1.750000
9 Belgium BE3194 GEL DOUCHE 500ML 9 1.500000
10 Belgium BE3194 GEL DOUCHE 500ML 10 1.500000
11 Belgium BE3194 GEL DOUCHE 500ML 11 5.500000
12 Belgium BE3194 GEL DOUCHE 500ML 12 1.500000
Then I have a second dataframe, products, containing all replenishment orders.
Product Date Quantity
0 BE3194 2020-09-01 600
1 BE3194 2021-06-01 400
I would like to append all monthly sales from grouper to products for the months between the first and last date in products. The output should look something like this:
Product Date Quantity
0 BE3194 2020-09-01 60
1 BE3194 2021-03-01 40
2 BE3194 2020-09-01 -1.5
3 BE3194 2020-10-01 -1.5
4 BE3194 2020-11-01 -5.5
5 BE3194 2020-12-01 -1.5
6 BE3194 2021-01-01 -3
7 BE3194 2021-02-01 -1.75
8 BE3194 2021-03-01 -2.33
My first idea was using a for loop combined with pd.date_range, something like this:
for entry in pd.date_range(product['Date'].min(),product['Date'].max(), freq='MS').tolist():
products.append(grouper[(grouper['Product'] == products['Product']) &
(grouper['Month'] == entry.dt.month)])
But I haven't managed to make it work so far. How can I best achieve this?