Calculating YoY growth for columns

Viewed 78

I am trying to calculate the YoY change between columns. Lets say I have the df below

datedf = pd.DataFrame({'ID':list('12345'),'1/1/2019':[1,2,3,4,5],'2/1/2019':[1,2,3,4,5],'3/1/2019':[1,2,3,4,5],'1/1/2020':[2,4,6,8,10],'2/1/2020':[2,4,6,8,10],'3/1/2020':[2,4,6,8,10]})

What transformation would I have to do in order to get to this result below, to show 100% gain YoY.

endingdf = pd.DataFrame({'ID':list('12345'),'1/1/2020':[1,1,1,1,1],'2/1/2020':[1,1,1,1,1],'3/1/2020':[1,1,1,1,1]})

This is the code I have tried but it does not work. The real data I am working with has multiple years.

just_dates = datedf.loc[:,'1/1/2019':]
just_dates.columns = pd.to_datetime(just_dates.columns)
just_dates.groupby(pd.Grouper(level=0,freq='M',axis=1),axis=1).pct_change()
1 Answers

Try this:

result = datedf.set_index('ID')
result.columns = pd.to_datetime(result.columns)
result = result.pct_change(periods=12, freq='MS', axis=1)

Result:

    2019-01-01  2019-02-01  2019-03-01  2020-01-01  2020-02-01  2020-03-01
ID                                                                        
1          NaN         NaN         NaN         1.0         1.0         1.0
2          NaN         NaN         NaN         1.0         1.0         1.0
3          NaN         NaN         NaN         1.0         1.0         1.0
4          NaN         NaN         NaN         1.0         1.0         1.0
5          NaN         NaN         NaN         1.0         1.0         1.0
Related