percentage change mean by group - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: percentage change mean by group (/thread-15238.html) |
percentage change mean by group - SriRajesh - Jan-09-2019 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() RE: percentage change mean by group - scidam - Jan-09-2019 (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() |