Pandas groupby multiple columns, with pct_change

you want to get your date into the row index and groups/company into the columns

d1 = df.set_index(['Date', 'Company', 'Group']).Value.unstack(['Company', 'Group'])
d1

enter image description here

then use pct_change

d1.pct_change()

enter image description here

OR

with groupby

df['pct'] = df.sort_values('Date').groupby(['Company', 'Group']).Value.pct_change()
df

enter image description here


I'm not sure the groupby method works as intended as of Pandas 0.23.4 at least.

df['pct'] = df.sort_values('Date').groupby(['Company', 'Group']).Value.pct_change()

Produces this, which is incorrect for purposes of the question:

Incorrect Outcome

The Index+Stack method still works as intended, but you need to do additional merges to get it into the original form requested.

d1 = df.set_index(['Date', 'Company', 'Group']).Value.unstack(['Company', 'Group'])
d1 = d1.pct_change().stack([0,1]).reset_index()
df = df.merge(d1, on=['Company', 'Group', 'Date'], how='left')
df.rename(columns={0: 'pct'}, inplace=True)
df

Correct Outcome


df['Pct_Change'] = df.groupby(['Company','Group'])['Value'].pct_change()