greenafrican
greenafrican

Reputation: 2546

Add rate of change column to Pandas DataFrame

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)?

Upvotes: 11

Views: 12409

Answers (1)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58915

You can use the diff method:

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

Upvotes: 15

Related Questions