I have a data set with values ('ee') of interest by quarter, and multiple fields which indicate the amount of ee in various subsets of the population, as follows:
test=pd.DataFrame(data={'cyq':['2018Q1']*3+['2018Q2']*3+['2018Q3']*3+['2018Q4']*3,
'species':['canine','canine','feline']*4,
'group':['a','b','a']*4,
'ee':range(12)})
I'm trying to get a rolling sum of ee over the quarters, specific to each unique subset of the other fields, in this case species, and group. In my actual data set, I have six identifying fields in total.
The following:
test.groupby(['cyq','species','group']).ee.rolling(window=2).sum()
is producing all NaNs. Other solutions which I've found end up rolling the sum within the each quarter, or only on one identifying field. My goal is to take a rolling sum that recognizes canine a, canine b, and feline a as distinct and rolls their ee values by quarter:
Thank you so much for the help. I feel like there's a simple solution, but variations on this question I've found here aren't working on my dataset.
EDIT: I've pieced together the following solution, but sure this can't be the most effective or efficient way to achieve the goal:
test=pd.DataFrame(data={'cyq':['2018Q1']*3+['2018Q2']*3+['2018Q3']*3+['2018Q4']*3,
'species':['canine','canine','feline']*4,
'group':['a','b','a']*4,
'ee':range(12)})
test['cyq']=test.cyq.apply(lambda x: pd.to_datetime(x))
test=test.groupby(['group','species','cyq']).sum().reset_index(level=2)
test=test.groupby(level=[i for i in range(test.index.nlevels)]).rolling('100D',min_periods=2,on='cyq').sum()
test.droplevel([i for i in range(int(test.index.nlevels/2))]).reset_index()
