Adding a column thats result of difference in consecutive rows in pandas
You could use diff
and pass -1
as the periods
argument:
>>> df = pd.DataFrame({"A": [9, 4, 2, 1], "B": [12, 7, 5, 4]})
>>> df["dA"] = df["A"].diff(-1)
>>> df
A B dA
0 9 12 5
1 4 7 2
2 2 5 1
3 1 4 NaN
[4 rows x 3 columns]
Use shift.
df['dA'] = df['A'] - df['A'].shift(-1)