Python Forum

Full Version: percentage change mean by group
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I want to calculate percentage change mean (and sum) by group.
import pandas as pd 
d = {'col1': ['B','A','B','C','H','C','A','B','H','H','B','B'],'col2': [2.6,1.5,2.0,2.4,4.1,5.9,2.9,8.7,2.9,3.6,2.3,2.3], 'col3': [3.8,2.1,2.9,3.5,2.9,9.3,8.3,5.6,7.3,1.9,1,1]}
df = pd.DataFrame(data=d)
df_avg=df.groupby(['col1']).mean() # this line works
df_pct_sum=df.groupby(['col1']).pct_change().sum()
df_pct_mean=df.groupby(['col1']).pct_change().mean()
The below two lines of code does not giving the percentage change sum or mean by group. How to get percentage change mean & sum by group?

df.groupby(['col1']).pct_change().sum()
df.groupby(['col1']).pct_change().mean()
(Jan-09-2019, 01:18 PM)SriRajesh Wrote: [ -> ]How to get percentage change mean & sum by group?
Just switch the order of applying .pct_change() and .mean() methods, i.e. try this:

df.groupby(['col1']).mean().pct_change()
df.groupby(['col1']).sum().pct_change()