pandas dataseries - How to address difference in days
<p>I have a pandas dataframe navTable whose index is a series of dates.</p>

<p>I needed to find the difference between the consecutive dates in index</p>

<pre><code>                 Delta  
2016-08-10       0.006619  
2016-08-12       0.006595  
2016-08-14       0.006595  
2016-08-17       0.006595  
2016-08-18       0.006595 
</code></pre>

<p>I want a new column <code>Days_Diff</code> which would give me difference in subsequent dates (in index). Therefore my output should look like this</p>

<pre><code>             Delta      Delta_Days
8/10/2016   0.006619    None 
8/12/2016   0.006595    2 
8/14/2016   0.006595    2 
8/17/2016   0.006595    3 
8/18/2016   0.006595    1 
</code></pre>

<p>I tried this first:</p>

<pre><code>navTable['Index'] = navTable.index
navTable['Days_Diff'] = navTable['Index'] - navTable['Index'].shift(1)
navTable['Delta_Days'] = navTable['Days_Diff'].days
</code></pre>

<p>Outright, this was not accepted as it was complaining about "days cannot be applied on Series"</p>

<p>So, I tried this:</p>

<pre><code>navTable['Index'] = navTable.index
navTable['Days_Diff'] = navTable['Index'] - navTable['Index'].shift(1)
navTable['Delta_Days'] = [ eachDayDiff.days for eachDayDiff in list(dataTable['Days_Diff']) ]
</code></pre>

<p>Understandably, it is complaining about the first element with is <code>Null</code>. </p>

<blockquote>
  <p>'NaTType' object has no attribute 'days'</p>
</blockquote>

<p>Question 1) Am I handling this scenario efficiently?
Question 2) How to I address </p>

<blockquote>
  <p>'NaTType' object has no attribute 'days'</p>
</blockquote>

<p>For the record, first element is of type <code>pandas.tslib.NaTType</code>
Rest are of type <code>pandas.tslib.Timedelta</code></p>

<p>Edit: formatting</p>

<p>Normally you will use the <code>diff()</code> function to calculate the adjacent difference and you can convert the index to a normal series and then use the <code>diff()</code> function which gives a series of <code>time delta</code> data type:</p>

<pre><code>df.index.to_series().diff()

# 2016-08-10      NaT
# 2016-08-12   2 days
# 2016-08-14   2 days
# 2016-08-17   3 days
# 2016-08-18   1 days
# dtype: timedelta64[ns]
</code></pre>

<p>To convert the time delta data type to numeric types:</p>

<pre><code>import numpy as np
df['Delta_Days'] = (df.index.to_series().diff() / np.timedelta64(1, 'D')).astype(float)

df

#              Delta  Delta_Days
#2016-08-10 0.006619         NaN
#2016-08-12 0.006595         2.0
#2016-08-14 0.006595         2.0
#2016-08-17 0.006595         3.0
#2016-08-18 0.006595         1.0
</code></pre>

python pandas time-series