Date, Brand, Indication,Geo, Type and values are column names Currently calculating rolling quarter using a function and datetime stamp the code used below is as follows, it is taking some time to execute the code is there any way to change or modify the codeRQ column is the rolling quarter column added..
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import datetime
#***Date parsing using datetime.stptime function***
dateparse = lambda x: pd.datetime.strptime(x, '%m/%d/%Y')
df = pd.read_csv('Demo for MAt.csv', index_col=0,
parse_dates=['Date'], date_parser=dateparse)
## importing data from csv file as dataframe
#Function to calculate the rolling sum for each record by date and other
levels
def RQ(x):
##Function checks whether the date is falling in the previous 3 months range
##and sums up if it is in the range**
RQS = df['Value'][
(df.index >= x.name - datetime.timedelta(days = 62))
& (df.index <= x.name)
& (df['Brand'] == x[0])
& (df['Indication'] == x[1])
& (df['Geo'] == x[2])
& (df['Type'] == x[3])
]
return RQS.sum()
##For each row the calculation is done using the apply function**
df['RQ'] = df.apply(RQ, axis=1)
#the below data frames has the input and expected output for a sample
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
inputdf = pd.DataFrame([['04/01/2016', 1,'A','National','Value',10],
['05/01/2016', 1,'A','National','Value',20], ['06/01/2016',
1,'A','National','Value',30]], columns=['Date',
'Brand','Indication','Geo','Type','Value'])
print inputdf
outputdf = pd.DataFrame([['04/01/2016', 1,'A','National','Value',10,10],
['05/01/2016', 1,'A','National','Value',20,30], ['06/01/2016',
1,'A','National','Value',30,60]], columns=['Date',
'Brand','Indication','Geo','Type','Value','RQ'])
print outputdf
#Input**Below input**
Date Brand Indication Geo Type Value
0 04/01/2016 1 A National Value 10
1 05/01/2016 1 A National Value 20
2 06/01/2016 1 A National Value 30
## Expected output
Date Brand Indication Geo Type Value RQ
0 04/01/2016 1 A National Value 10 10
1 05/01/2016 1 A National Value 20 30
2 06/01/2016 1 A National Value 30 60