将变化率添加到 Pandas DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19837352/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:18:59  来源:igfitidea点击:

Add rate of change to Pandas DataFrame

pythonnumpypandas

提问by greenafrican

I have the following Pandas DataFrame:

我有以下 Pandas DataFrame:

    lastrun                                value 
0   2013-10-24 13:10:05+00:00              55376
1   2013-10-24 14:10:32+00:00              56738
2   2013-10-24 15:52:31+00:00              58239
3   2013-10-24 23:52:09+00:00              59981
4   2013-10-25 00:52:04+00:00              61001

I would like to add a column into the dataframe with the rate of change so that i end up with:

我想以变化率在数据框中添加一列,以便我最终得到:

    lastrun                                value    change 
0   2013-10-24 13:10:05+00:00              55376    NaN
1   2013-10-24 14:10:32+00:00              56738    1362
2   2013-10-24 15:52:31+00:00              58239    1501
3   2013-10-24 23:52:09+00:00              59981    1742
4   2013-10-25 00:52:04+00:00              61001    1020

I know the percentage change can be found using pct_change() but I don't know how to include it as a new column in the existing DataFrame and I'm looking for the real value in change and not the % change.

我知道可以使用 pct_change() 找到百分比变化,但我不知道如何将其作为新列包含在现有 DataFrame 中,我正在寻找变化的真实值而不是变化百分比。

What is the most effective way to achieve this in pandas (or python, numpy)?

在 Pandas(或 python、numpy)中实现这一目标的最有效方法是什么?

回答by Saullo G. P. Castro

You can use the diffmethod:

您可以使用以下diff方法:

df['new_column'] = df['source_column'].diff()