Python Forum
How to calculate percentage change sum (Mean) by group - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to calculate percentage change sum (Mean) by group (/thread-15184.html)



How to calculate percentage change sum (Mean) by group - SriRajesh - Jan-07-2019

Hi,

I have below DataFrame:

A 1.2  3.6
B 2.6  3.8 
A 1.5  2.1
B 2.0  2.9
C 2.4  3.5
H 4.1  2.9
C 5.9  9.3
A 2.9  8.3
B 8.7  5.6
H 2.9  7.3
H 3.6  1.9
B 2.3  1.0
A 7.1  2.3
I use blow code:
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=df.groupby(['col1']).pct_change.sum()
AttributeError: 'function' object has no attribute 'sum'


RE: How to calculate percentage change sum (Mean) by group - snippsat - Jan-07-2019

pct_change is a function(),so try pct_change().sum().


RE: How to calculate percentage change sum (Mean) by group - SriRajesh - Jan-07-2019

I modified my code, it works, but I need the output by group.
df_pct=df.groupby(['col1']).pct_change().sum()

The above line of code does only giving the pct_change sum by column (but I want to by column & by group).

The below output is of: df_avg=df.groupby(['col1']).mean()

col1	col2	col3
A	    2.20	5.20
B	    3.57	2.86
C	    4.15	6.40
H	    3.50	4.03

Similarly I want pct_change().sum() by group




RE: How to calculate percentage change sum (Mean) by group - SriRajesh - Jan-09-2019

df_pct=df.groupby(['col1']).pct_change().sum() 
The above line of code does not giving the "percentage change sum" of each column by group. How to get "percentage change sum" or "percentage change mean" of each column by group.