python - Computing percentage difference between pandas dataframe rows -
region year val 1.0 2015.0 6.775457e+05 1.0 2016.0 6.819761e+05 1.0 2017.0 6.864065e+05 2.0 2015.0 6.175457e+05 2.0 2016.0 6.419761e+05 3.0 2017.0 6.564065e+05
in dataframe above, want compute percentage difference between consecutive rows same region values. tried not sure if works. best way achieve it?
df.groupby(['region', 'year'])['val'].pct_change()
you can use dataframegroupby.pct_change
groupby column region
:
df['new'] = df.groupby('region')['val'].pct_change() print (df) region year val new 0 1.0 2015.0 677545.7 nan 1 1.0 2016.0 681976.1 0.006539 2 1.0 2017.0 686406.5 0.006496 3 2.0 2015.0 617545.7 nan 4 2.0 2016.0 641976.1 0.039560 5 3.0 2017.0 656406.5 nan
Comments
Post a Comment