How can I calculate the time (number of days) between "events" in a Pandas time series? For example, if I have the below time series I'd like to know on each day in the series how many days have passed since the last TRUE
event
2010-01-01 False
2010-01-02 True
2010-01-03 False
2010-01-04 False
2010-01-05 True
2010-01-06 False
The way I've done it seems overcomplicated, so I'm hoping for something more elegant. Obviously a for loop iterating over the rows would work, but I'm looking for a vectorized (scalable) solution ideally. My current attempt below:
date_range = pd.date_range('2010-01-01', '2010-01-06')
df = pd.DataFrame([False, True, False, False, True, False], index=date_range, columns=['event'])
event_dates = df.index[df['event']]
df2 = pd.DataFrame(event_dates, index=event_dates, columns=['max_event_date'])
df = df.join(df2)
df['max_event_date'] = df['max_event_date'].cummax(axis=0, skipna=False)
df['days_since_event'] = df.index - df['max_event_date']
event max_event_date days_since_event
2010-01-01 False NaT NaT
2010-01-02 True 2010-01-02 0 days
2010-01-03 False 2010-01-02 1 days
2010-01-04 False 2010-01-02 2 days
2010-01-05 True 2010-01-05 0 days
2010-01-06 False 2010-01-05 1 days