Nis Nis - 4 months ago 16
Python Question

Dividing a Pandas series with the same series shifted one place

I have a Pandas series, a time and a value.
I would like to calculate the changes between each value.
Like this: current value / previous value.

When I run this code:

print now.head(n=3)
print before.head(n=3)
delta = now.divide(before)
print delta.iloc[1]
print now.iloc[1] / before.iloc[1]

I get this result:

2014-01-08 09:27:00 623.53836
2014-01-08 09:28:00 623.54066
2014-01-08 09:32:00 623.53846
Name: close, dtype: float64
2014-01-08 09:26:00 624.01000
2014-01-08 09:27:00 623.53836
2014-01-08 09:28:00 623.54066
Name: close, dtype: float64

What am I missing since the last two numbers are not the same?

The series now and before are the same series, only shifted one place.

Update: The problem was the indexes which pandas matches when dividing. Luckily pandas has the built-in function called .pct_change() that does exactly what I want. Thank you Steven G. for showing me that.


the problem is that when you do delta = now.divide(before)it will match indexes. so delta.iloc[1] will be 623.53836 / 623.53836 representing the division on 2014-01-08 09:27:00 index

when you use integer location now.iloc[1] / before.iloc[1] it doesn't care about the index so it does 623.54066 / 623.53836

remember that .iloc[1] is the second row and .iloc[0] is the first row