pandas 如何根据精确匹配的日期值过滤熊猫数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46452961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter pandas dataframe based on date value with exact match
提问by Waqar
I have been trying to filter my data frame for the specific date although the date is present in the data frame but it doesn't return any results
我一直在尝试过滤特定日期的数据框,尽管数据框中存在日期但它没有返回任何结果
Data in Data frame based on query
基于查询的数据框中的数据
df[df['Date'] > '2017-03-20']
returns this results
返回这个结果
StaffID Date
90047 2017-03-20 19:00:00
90049 2017-03-20 19:00:00
90049 2017-03-27 19:00:00
although when i am running this query
虽然当我运行这个查询时
df[df['Date'] == '2017-03-20']
or
或者
df.loc[df['Date'] == '2017-03-20']
it returns me no results at all just an empty data frame
它根本没有返回任何结果,只是一个空的数据框
StaffID Date
my data frame column types are
我的数据框列类型是
StaffID int64
Date datetime64[ns]
and i have tried above query by comparing data frame date with string as well as by converting the string dateinto datetime64[ns]still the same results any help please would be appreciated
我已经通过将数据框日期与字符串进行比较以及将字符串日期转换为datetime64[ns]来尝试上述查询,结果仍然相同,请提供任何帮助,我们将不胜感激
采纳答案by Bharath
Use dt.date astype string then compare i.e
使用 dt.date astype string 然后比较即
df[df['Date'].dt.date.astype(str) == '2017-03-20']
Output:
输出:
StaffID Date 0 90047 2017-03-20 19:00:00 1 90049 2017-03-20 19:00:00
回答by Waqar
The date i was using is '2017-03-20 19:00:00'which is > than '2017-03-20 00:00:00'thats why it wasn't comparing it right the best way to do it is
我使用的日期是“2017-03-20 19:00:00”,它大于“2017-03-20 00:00:00”,这就是为什么它没有正确比较它的最佳方法是
df.Date = df.Date.dt.date
dateToMatch = np.datetime64('2017-03-20')
df[df.Date == dateToMath]
above code returns
上面的代码返回
StaffID Date
0 90047 2017-03-20
1 90049 2017-03-20
this will only extract date from my date column and replace the old column which had time
这只会从我的日期列中提取日期并替换有时间的旧列
Credit: Wen who answered me in comment.
信用:在评论中回答我的文。
回答by Vaishali
You can do string comparison
您可以进行字符串比较
df[df['Date'].astype(str).str[:10] == '2017-03-20']
StaffID Date
0 90047 2017-03-20 19:00:00
1 90049 2017-03-20 19:00:00