首页 > 解决方案 > How to calculate Growth rate of a time series variable in python pandas

问题描述

I have a data in time series format like:

date          value
1-1-2013       100
1-2-2013       200 
1-3-2013       300
1-4-2013       400
1-5-2013       500
1-6-2013       600
1-7-2013       700
1-8-2013       650
1-9-2013       450
1-10-2013      350
1-11-2013      250
1-12-2013      150 

标签: pandas

解决方案


Use Series.pct_change:

In [458]: df['growth rate'] = df.value.pct_change()

In [459]: df
Out[459]: 
         date  value  growth rate
0    1-1-2013    100          NaN
1    1-2-2013    200     1.000000
2    1-3-2013    300     0.500000
3    1-4-2013    400     0.333333
4    1-5-2013    500     0.250000
5    1-6-2013    600     0.200000
6    1-7-2013    700     0.166667
7    1-8-2013    650    -0.071429
8    1-9-2013    450    -0.307692
9   1-10-2013    350    -0.222222
10  1-11-2013    250    -0.285714
11  1-12-2013    150    -0.400000

Or:

If you want to show in percent multiply by 100:

In [480]: df['growth rate'] = df.value.pct_change().mul(100)

In [481]: df
Out[481]: 
         date  value  growth rate
0    1-1-2013    100          NaN
1    1-2-2013    200   100.000000
2    1-3-2013    300    50.000000
3    1-4-2013    400    33.333333
4    1-5-2013    500    25.000000
5    1-6-2013    600    20.000000
6    1-7-2013    700    16.666667
7    1-8-2013    650    -7.142857
8    1-9-2013    450   -30.769231
9   1-10-2013    350   -22.222222
10  1-11-2013    250   -28.571429
11  1-12-2013    150   -40.000000

推荐阅读