Dividing a Pandas series with the same series shifted one place
<p>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.</p>

<p>When I run this code:</p>

<pre><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]
</code></pre>

<p>I get this result:</p>

<pre><code>DateTime
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
DateTime
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
1.0
1.00000368863
</code></pre>

<p>What am I missing since the last two numbers are not the same?</p>

<p>The series now and before are the same series, only shifted one place. </p>

<p><strong>Update</strong>: 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.</p>

<p>You could divide by the values:</p>

<pre><code>now['delta'] = now.values / before.values
</code></pre>

<p>This will add a new column to your now dataframe of course. </p>

<p>Alternately, if you want this in its own dataframe you could write:</p>

<pre><code>delta = now.copy()
delta['delta'] = now.close.values / before.close.values
delta.drop('close', 1, inplace=True)
</code></pre>

python pandas