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>Count the seconds:</p>

<pre><code>cumsecs = df.datetime.diff().astype('timedelta64[s]').cumsum().fillna(value=0.0)
</code></pre>

<p>Copy the cumulative value whenever delivered fails, and fill any preceeding values:</p>

<pre><code>undeliv_secs = cumsecs.where(~df['delivered']).fillna(method='bfill')
</code></pre>

<p>Seconds until failure is just the difference between the two:</p>

<pre><code>df['secondsuntilfailure'] = undeliv_secs - cumsecs
print(df)
             datetime delivered  secondsuntilfailure
0 2014-05-01 01:00:00      True                  3.0
1 2014-05-01 01:00:01      True                  2.0
2 2014-05-01 01:00:02      True                  1.0
3 2014-05-01 01:00:03     False                  0.0
4 2014-05-01 01:00:04      True                  NaN
</code></pre>

python datetime pandas