am having one dataframe, dataframe has 16 columns cust_id, order_id, value, date, jan,feb,mar,apr -- dec columns
Using group by cust_id & order_id - I have to implement multiply & add a calculation for each current row and previous row of Values column & Jan feb mar apr may -- dec columns based on date column
If previous month values are not present, that particular month should be considered as 0 like for Ex: In date column first row was starting from 12th[Dec] month so previous month value November is not existed in dataframe for that calculation should be 0 below calculation shows if any of previous month values are not there
groupby[1008,001] date[dec month] calculation = output = 1000*0.4 + 0 =400
Input Dataframe
import pandas as pd
import numpy as np
import datetime
df = pd.DataFrame({'cust_id': ['1008'] * 4 + ['1009'] *4,
'order_id': ['51'] * 4 + ['192'] * 4,
'Date': ["2020-12-01",
"2021-01-01",
"2021-02-01",
"2021-03-01",
"2020-12-01",
"2021-01-01",
"2021-02-01",
"2021-03-01"],
'Value': [1000, 2000, 3000, 3000, 6000, 9000, 180, 400],
'Dec': [0.1]*2+ [0]*2 + [0.5]*2 + [0.5]*2,
'Jan': [0.1]*2+ [0.5]*2 + [0.3]*2 + [0]*2,
'Feb': [0.2]*2+ [0]*2 + [0.1]*2 + [0.5]*2,
'Mar': [0.8]*2+ [0.4]*2 + [0.1]*2 + [0.2]*2,
'Apr': [0.3]*2+ [0.5]*2 + [0.4]*2 + [0.6]*2})
Output Dataframe
data
###
cust_id order_id date value output
1008 001 2020-12-01 1000 400 [1000*0.4 + 0]
1008 001 2020-01-01 2000 1100 [2000*0.5 + 1000*0.1]
1008 001 2020-02-01 3000 0 [3000*0+2000*0]
2007 009 2021-02-01 3000 0
2007 009 2021-03-01 6000 1500
2007 009 2021-04-01 9000 2700
I tried the below code but not working
df['output'] = df.groupby['cust_id','order_id']['Date'].apply(lambda x:(x['values']*x['jan']+x['values']*x['dec']))
but in loop it should work with jan,feb,mar -- dec
Even i tried below one as well
df_1 = pd.DataFrame(
(df.Value * df[4:][:, None]).reshape(-1, df.shape[1]),
pd.MultiIndex.from_product([df.index, df.index]),
df.columns
)
df_1