pandas - 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
解决方案
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
推荐阅读
- php - 如何使用 DQL/Query Builder 在 MS-SQL 中使用 DATE_FORMAT
- python - ImportError:通过虚拟机上的 apache2 和 wsgi 提供烧瓶应用程序时,无法从“flask”导入名称“request”
- c++ - 如何在 C++ 中实现干净的架构组件边界?
- php - 在 mysql/php 中每小时以 100 个批量显示海量数据
- excel - Excel:提供一个分割范围作为一个输入
- javascript - 尽管有异步/等待,但在返回后调用 nestJS Mongoose 回调
- java - JBoss 中的异步 JAX-RS
- authentication - 使用 IIS 自定义 HTTP 模块的 .Net 反向代理的 Windows 身份验证问题
- django - 如何更新 Django 中的现有记录?
- javascript - 如何在 React 中打印 base64 格式的 svg 元素?