pandas 过滤和比较日期 [英] pandas filtering and comparing dates
问题描述
我有一个sql文件,其中包含我要读入熊猫的数据.
I have a sql file which consists of the data below which I read into pandas.
df = pandas.read_sql('Database count details', con=engine,
index_col='id', parse_dates='newest_available_date')
输出
id code newest_date_available
9793708 3514 2015-12-24
9792282 2399 2015-12-25
9797602 7452 2015-12-25
9804367 9736 2016-01-20
9804438 9870 2016-01-20
代码的下一行是获取上周的日期
The next line of code is to get last week's date
date_before = datetime.date.today() - datetime.timedelta(days=7) # Which is 2016-01-20
我想做的是,将date_before
与df
进行比较,并打印出所有小于date_before
What I am trying to do is, to compare date_before
with df
and print out all rows that is less than date_before
if (df['newest_available_date'] < date_before):
print(#all rows)
if (df['newest_available_date'] < date_before):
print(#all rows)
显然,这会给我返回错误The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Obviously this returns me an error The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我应该怎么做?
推荐答案
我会做一个面具:
a = df[df['newest_date_available'] < date_before]
如果为date_before = datetime.date(2016, 1, 19)
,则返回:
id code newest_date_available
0 9793708 3514 2015-12-24
1 9792282 2399 2015-12-25
2 9797602 7452 2015-12-25
这篇关于 pandas 过滤和比较日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!