Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percent change on a Pandas DataFrame

I have the following DataFrame:

                 Value        1lag 
Date                                                                     
2005-04-01  258.682029  214.382786 
2005-05-01  173.253998  258.682029
2005-06-01  244.432029  173.253998
2005-07-01  213.706019  244.432029
2005-08-01  213.670665  213.706019

Those are absolute values of two time series. However, I don't want those absolute values, I want the variations of them, so they get to look like this:

                 Value        1lag 
Date                                                                     
2005-04-01         NaN         NaN 
2005-05-01      0.3302     -0.2066
2005-06-01     -0.4108      0.3302
2005-07-01      0.1257     -0.4108
2005-08-01      0.0002      0.1257

Is there an easy command to do that? If not, what would be your suggestion to achieve that result?

like image 999
aabujamra Avatar asked Dec 04 '22 01:12

aabujamra


2 Answers

You can just use pct_change() on the dataframe.

>>> df.pct_change()
               Value      1lag
Date                          
2005-04-01       NaN       NaN
2005-05-01 -0.330243  0.206636
2005-06-01  0.410831 -0.330243
2005-07-01 -0.125704  0.410831
2005-08-01 -0.000165 -0.125704

Comparing the results above with yours, you would need to use -df.pct_change() if you want reverse the change as you have done.

like image 121
Alexander Avatar answered Jan 08 '23 12:01

Alexander


Something like this?

>>> 1 - df / df.shift(1)
               Value      1lag
Date                          
2005-04-01       NaN       NaN
2005-05-01  0.330243 -0.206636
2005-06-01 -0.410831  0.330243
2005-07-01  0.125704 -0.410831
2005-08-01  0.000165  0.125704
like image 37
Roman Pekar Avatar answered Jan 08 '23 12:01

Roman Pekar