Skip to content

Instantly share code, notes, and snippets.

@wbhinton
Last active December 12, 2019 17:50
Show Gist options
  • Save wbhinton/5a9db7f886c86f0ae16c5633ba2f7500 to your computer and use it in GitHub Desktop.
Save wbhinton/5a9db7f886c86f0ae16c5633ba2f7500 to your computer and use it in GitHub Desktop.
Calculate the percent change of a value within a group
#This first method calculates the percent change from previous observation with in a group.
#An example: The change in a patient's lab value from obs to obs overtime
#The DF should have a field that you want to group, a time range, and value you want
# to perform the calculation on.
# first step is to order the DF by the Group, then by time
df = df.sort(['GroupID','time'])
# step two performs the calculation.
df['pct_chg']=df.groupby('GroupID)['Value'].pct_change()
# Method 2 % change from the inital to final observation
init_final = grouped.agg([("pct change", lambda x: (x.iloc[-1] - x.iloc[0]) / x.iloc[0])])
# Method 3 % change from initial to the max value
max_init = grouped.agg([("pct change", lambda x: (x.max() - x.iloc[0]) / x.iloc[0])])
# Method 4 % change from min to max within the group.
gmm = grouped.agg([("pct change", lambda x: (x.max() - x.min()) / x.min())])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment