为Pandas DataFrame添加更改率

gre*_*can 6 python numpy pandas

我有以下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
Run Code Online (Sandbox Code Playgroud)

我想在数据框中添加一个列,其中包含更改率,以便最终得到:

    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
Run Code Online (Sandbox Code Playgroud)

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

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

Sau*_*tro 8

您可以使用以下diff方法:

df['new_column'] = df['source_column'].diff()
Run Code Online (Sandbox Code Playgroud)