I would like to get the year on year quarterly change in Value1 and Value 2
df =\
pd.DataFrame({'Year':[2010,2010,2010,2010,2009,2009,2009,2009],
'Quarter':[1,1,2,2,1,1,2,2],
'Section':['A', 'B', 'A', 'B','A', 'B','A', 'B'],
'Value1': [1,2,3,4,5,6,7,8],
'Value2':[10,20,30,40,50,60,70,80]
})
df.set_index(['Year', 'Quarter', 'Section'], inplace=True)
df
Currently I am doing this:
##Not ideal
df_2009 =\
(df
.reset_index()
.where(lambda x: x.Year == 2009)
.dropna()
.astype({'Quarter':'int16'})
.set_index(['Quarter', 'Section'])
.drop('Year', axis=1)
)
df_2010 =\
(df
.reset_index()
.where(lambda x: x.Year == 2010)
.dropna()
.astype({'Quarter':'int16'})
.set_index(['Quarter', 'Section'])
.drop('Year', axis=1)
)
df_2010/df_2009
However, it is not scalable. I wonder it there's better way to do this. e.g. pandas functions or UDF
p.s. the result is created by
(somedata
.groupby(['Year', 'Quarter', 'Section'])
.agg({'Value1':'sum',
'Value2':'sum'})
)