konichiwa
konichiwa

Reputation: 551

How to add a column in pandas DataFrame with boolean result of datetime comparison?

How can I create an extra column in a Pandas DataFrame that contains the result (boolean) of the following date comparison?

records['old'] = TRUE if records['date'] is older than 180 days
records['old'] = FALSE if records['date'] is not older than 180 days

Code

today = datetime.now()
records['old'] = records[abs(today - pd.to_datetime(records['date'])) > 180]

Output

TypeError: invalid type comparison

Upvotes: 1

Views: 680

Answers (1)

jezrael
jezrael

Reputation: 862731

I think you need pd.Timedelta or dt.days:

records['old'] = abs(today - pd.to_datetime(records['date'])) > pd.Timedelta(180, unit='d')

Or:

records['old'] = abs(today - pd.to_datetime(records['date'])).dt.days > 180

Sample:

rng = pd.date_range('2017-12-30', periods=10)
records = pd.DataFrame({'date': rng, 'a': range(10)})  

today = pd.datetime.now()
records['old'] = abs(today - pd.to_datetime(records['date'])) > pd.Timedelta(5, unit='d')
print (records)
   a       date    old
0  0 2017-12-30   True
1  1 2017-12-31   True
2  2 2018-01-01   True
3  3 2018-01-02   True
4  4 2018-01-03   True
5  5 2018-01-04   True
6  6 2018-01-05   True
7  7 2018-01-06  False
8  8 2018-01-07  False
9  9 2018-01-08  False

Upvotes: 1

Related Questions