'Pandas: Calculate neighbouring differences from a column in dataframe
How can I calculate the differences from neighboured numbers in a dataframe column named 'y' by only using Pandas commands?
Here is an example where I convert the column 'y'first to numpy and then use np.diff.
import numpy as np
import pandas as pd
np.random.seed(10)
df = pd.DataFrame(np.random.randint(0,10,size=(10,2)),columns=['x', 'y'])
y=df['y'].values
diff_y=np.diff(y)
print(np.array([y[0:-1],diff_y]).T)
[[ 4 -3]
[ 1 -1]
[ 0 8]
[ 8 -8]
[ 0 6]
[ 6 -3]
[ 3 1]
[ 4 4]
[ 8 0]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
