Python Pandas calculate time until output reaches 0
<p>I have a pandas dataframe in python with several columns and a datetime stamp. One of the columns has a true/false variable. I'd like to calculate time until that column is false.</p>

<p>Ideally it would look something like this:</p>

<pre><code>datetime             delivered    secondsuntilfailure
2014-05-01 01:00:00    True       3
2014-05-01 01:00:01    True       2
2014-05-01 01:00:02    True       1
2014-05-01 01:00:03    False      0
2014-05-01 01:00:04    True       ?
</code></pre>

<p>Thanks in advance!!</p>

<p>You can first change order by <code>[::-1]</code>, then find <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow"><code>diff</code></a> and count <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="nofollow"><code>cumsum</code></a> if values are <code>True</code>:</p>

<pre><code>df = df[::-1]
print (df.datetime.diff().astype('timedelta64[s]'))
4    NaN
3   -1.0
2   -1.0
1   -1.0
0   -1.0
Name: datetime, dtype: float64

df['new'] = df.delivered.where(~df.delivered,df.datetime.diff().astype('timedelta64[s]'))
              .cumsum().fillna(0).astype(int).mul(-1)
df = df[::-1]
print (df)
             datetime delivered secondsuntilfailure  new
0 2014-05-01 01:00:00      True                   3    3
1 2014-05-01 01:00:01      True                   2    2
2 2014-05-01 01:00:02      True                   1    1
3 2014-05-01 01:00:03     False                   0    0
4 2014-05-01 01:00:04      True                   ?    0
</code></pre>

python datetime pandas