Create a boolean dataframe based on the difference between two datetimes

Viewed 366

I have a pandas dataframe called "gaps" that looks like this:

Index    Gap in days
0        2 days 00:00:00
1        8 days 00:00:00
2        4 days 00:00:00
3        15 days 00:00:00
...
201      21 days 00:00:00

The date format has been converted to the standard datetime format. I want to create a simple boolean dataframe that returns TRUE if the gap in days is more than 7 days, and FALSE otherwise.

My initial attempt was the simple:

morethan7days = gaps > 7

For which I get the error:

TypeError: invalid type comparison

Anybody know what I'm doing wrong and how to fix it?

2 Answers

Nevermind, I got the answer through trial and error:

morethan7days = gaps > datetime.timedelta(days=7)

You can convert timedeltas to days by Series.dt.days and then compare by integer:

gaps = df['Gap in days']
morethan7days = gaps.dt.days > 7
print (morethan7days)
0    False
1     True
2    False
3     True
4     True
Name: Gap in days, dtype: bool

Another solution is compare with pandas.Timedelta:

gaps = df['Gap in days']
morethan7days = gaps > pd.Timedelta(7, unit='d')
Related