I have a pandas DataFrame df (gradient is the new calculated column):
Time Value1 Value2 gradient
1 20 40 NaN
2 30 100 0.5
3 36 150 0.2
4 18 100 -0.5
Now, I want to calculate all differences between the row y and the prior row x, divided by the value in the prior row.
Example: in this case, in the new column df['gradient'] should I get in row 3 for 'value1' : 0.20 --> ((36-30) / 30)
I have now:
df['gradient'] = df['Value1'].diff() / df['Value1']
But I know the / df['Value1'] is not correct. What's the right syntax in this case for dividing by the value in the prior row?
You can shift() the column that you divide by. This moves each value into the next row down. For example if you have your df as:
Value1
0 20
1 30
2 36
3 18
Then the gradients can be calculated with the division:
>>> df.Value1.diff() / df.Value1.shift()
0 NaN
1 0.5
2 0.2
3 -0.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With