Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add rate of change column to Pandas DataFrame

Tags:

python

pandas

I have the following 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, to get:

    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.

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

like image 989
greenafrican Avatar asked Nov 07 '13 13:11

greenafrican


Video Answer


1 Answers

You can use the diff method:

df['new_column'] = df['source_column'].diff()
like image 122
Saullo G. P. Castro Avatar answered Oct 19 '22 10:10

Saullo G. P. Castro