Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
df = pd.DataFrame({'p': [2, 3, 4, 5, 6, 7],
                   'q': [2, 2, 3, 5, 8, 10],
                   'r': [4, 9, 16, 24, 36, 40]})
df
Out[2]:
p q r
0 2 2 4
1 3 2 9
2 4 3 16
3 5 5 24
4 6 8 36
5 7 10 40

Pandas: Dataframe - diff.

In [3]:
df.diff()
Out[3]:
p q r
0 NaN NaN NaN
1 1.0 0.0 5.0
2 1.0 1.0 7.0
3 1.0 2.0 8.0
4 1.0 3.0 12.0
5 1.0 2.0 4.0

Pandas: Dataframe - diff().

Difference with previous column:

In [4]:
df.diff(axis=1)
Out[4]:
p q r
0 NaN 0.0 2.0
1 NaN -1.0 7.0
2 NaN -1.0 13.0
3 NaN 0.0 19.0
4 NaN 2.0 28.0
5 NaN 3.0 30.0

Pandas: Dataframe - Difference with previous column.

Difference with 3rd previous row:

In [5]:
df.diff(periods=3)
Out[5]:
p q r
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 3.0 3.0 20.0
4 3.0 6.0 27.0
5 3.0 7.0 24.0

Pandas: Dataframe - Difference with 3rd previous row.

Difference with following row:

In [6]:
df.diff(periods=-1)
Out[6]:
p q r
0 -1.0 0.0 -5.0
1 -1.0 -1.0 -7.0
2 -1.0 -2.0 -8.0
3 -1.0 -3.0 -12.0
4 -1.0 -2.0 -4.0
5 NaN NaN NaN

Pandas: Dataframe - Difference with following row.