1

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.