data = {'machine_id': [1000,1000,3000,2000,3000,1000,1000,3000,2000,3000,1000,1000,3000,2000,3000,1000,2000],
'item_id': [100,100,100,200,300,100,100,100,200,300,100,100,100,200,300,100,200],
'Date': ['2022-03-01','2022-03-02','2022-03-03','2022-03-04','2022-03-05',
'2022-04-01','2022-04-02','2022-04-03','2022-04-04','2022-04-05',
'2022-05-01','2022-05-02','2022-05-03','2022-05-04','2022-05-05','2022-03-06','2022-03-10'],
'Sales_qty':[5,6,5,7,8,1,3,7,9,6,4,7,8,9,4,5,8]}
df = pd.DataFrame(data)
df['total']=df.groupby(['machine_id','item_id','Date'])['Sales_qty'].transform('sum')
df['sales_avg']=df['Sales_qty']/df['total']
in output column i want last month sales avg.
|machine_id|item_id|Date|Sales_qty|total|current_sales_avg| last_month_avg|
0 1000 100 2022-03-01 5 13 0.384615 NaN
1 1000 100 2022-03-01 6 13 0.461538 NaN
2 3000 100 2022-03-01 5 5 1.000000 NaN
3 2000 200 2022-03-01 7 10 0.700000 NaN
4 3000 300 2022-03-01 8 8 1.000000 NaN
5 1000 100 2022-04-01 1 4 0.250000 0.384615
6 1000 100 2022-04-01 3 4 0.750000 0.461538
7 3000 100 2022-04-01 7 7 1.000000 1.000000
8 2000 200 2022-04-01 9 9 1.000000 0.700000
9 3000 300 2022-04-01 6 6 1.000000 1.000000
10 1000 100 2022-05-01 4 11 0.363636 0.250000
11 1000 100 2022-05-01 7 11 0.636364 0.750000
12 3000 100 2022-05-01 8 8 1.000000 1.000000
13 2000 200 2022-05-01 9 9 1.000000 1.000000
14 3000 300 2022-05-01 4 4 1.000000 1.000000
15 1000 100 2022-03-06 2 13 0.153846 Nan
16 2000 200 2022-03-10 3 10 0.300000 Nan
Need code get the output. For March month the sales avg will be nan because we dont have feb month data. For april month we have last month data that is of march and for may month we have april month data.