如何在Pandas DataFrame中创建一个包含以下日期比较结果(布尔值)的额外列?
records['old'] = TRUE if records['date'] is older than 180 days
records['old'] = FALSE if records['date'] is not older than 180 days
代码
today = datetime.now()
records['old'] = records[abs(today - pd.to_datetime(records['date'])) > 180]
输出
TypeError:无效的类型比较
答案 0 :(得分:1)
我认为您需要pd.Timedelta
或dt.days
:
records['old'] = abs(today - pd.to_datetime(records['date'])) > pd.Timedelta(180, unit='d')
或者:
records['old'] = abs(today - pd.to_datetime(records['date'])).dt.days > 180
样品:
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