Calculating percentage change in pandas dataframe compared to baseline value

Viewed 1223

I have a pandas dataframe and I'd like to calculate the percentage difference compared to the beginning value. Is there a way to use pct_change() to complete this task?

e.g

my data

 date         close
2020-05-08    100
2020-05-11    102
2020-05-12    108

I'd like the change to appear like

 date         close  change (%)
2020-05-08    100     0
2020-05-11    102     2
2020-05-12    108     8
3 Answers

You can do

df['change'] = df['close'].div(df['close'].iloc[0]).sub(1).mul(100)

or

df['change'] = (df.close/df.close.iloc[0] - 1) * 100

Output:

         date  close  change
0  2020-05-08    100     0.0
1  2020-05-11    102     2.0
2  2020-05-12    108     8.0

Yes, this can be done using pct_change().

df['change'] = (df['close'].pct_change().fillna(0).add(1).cumprod().sub(1))*100

If you don't care about direction (+/-), then you can also take the absolute value:

df['change'] = (df['close'].pct_change().fillna(0).add(1).cumprod().sub(1).abs())*100

Edit: as David suggested, there are better solutions than this. I will leave the answer so you guys and girls know what not to do :).

You can always use an extra column to help. It's fairly easy:

start_value = 100 #or access through the index

df['beginning'] = start_value
df['change (%)'] = 100 * (df.close/df.beginning - 1)
df

Output:

    date    close   beginning   change (%)
0   2020-05-08  100     100     0.0
1   2020-05-11  102     100     2.0
2   2020-05-12  108     100     8.0
Related