计算 Pandas DataFrame 的百分比变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35181265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate percent change on a Pandas DataFrame
提问by abutremutante
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?
有没有一个简单的命令来做到这一点?如果没有,您对实现该结果的建议是什么?
回答by Alexander
You can just use pct_change()
on the dataframe.
您可以只pct_change()
在数据框上使用。
>>> 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.
将上面的结果与您的结果进行比较,-df.pct_change()
如果您想像所做的那样逆转更改,则需要使用。
回答by Roman Pekar
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
回答by Harold Henson
You can replicate Alexander's response with the code below. I am afraid Roman's response has the wrong sign
您可以使用以下代码复制 Alexander 的回复。恐怕罗曼的回应有错误的迹象
>>> (df-df.shift(1))/df.shift(1)
Value 1lag
2011-01-31 NaN NaN
2011-02-28 -0.330243 0.206636
2011-03-31 0.410831 -0.330243
2011-04-30 -0.125704 0.410831
2011-05-31 -0.000165 -0.125704