筛选并比较日期与 pandas [英] Filtering and comparing dates with Pandas

查看:72
本文介绍了筛选并比较日期与 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在所有不同的时间级别过滤不同的日期,即按年,月,日,时,分和/或日查找日期.例如,如何查找2014年或2014年1月或仅2014年1月2日或...直到第二天的所有日期?

I would like to know how to filter different dates at all the different time levels, i.e. find dates by year, month, day, hour, minute and/or day. For example, how do I find all dates that happened in 2014 or 2014 in the month of January or only 2nd January 2014 or ...down to the second?

所以我有从 pd.to_datetime

df
    timeStamp
0   2014-01-02 21:03:04
1   2014-02-02 21:03:05
2   2016-02-04 18:03:10

因此,如果按2014年进行过滤,则输出为:

So if I filter by the year 2014 then I would have as output:

    timeStamp
0   2014-01-02 21:03:04
1   2014-02-02 21:03:05

或者作为另一个示例,我想知道2014年发生的日期以及每个月的2号.这还会导致:

Or as a different example I want to know the dates that happened in 2014 and at the 2nd of each month. This would also result in:

    timeStamp
0   2014-01-02 21:03:04
1   2014-02-02 21:03:05

但是,如果我要询问2014年1月2日发生的日期

But if I asked for a date that happened on the 2nd of January 2014

    timeStamp
0   2014-01-02 21:03:04

如何在所有不同级别上实现这一目标?

How can I achieve this at all the different levels?

您还如何比较这些不同级别的日期以创建布尔索引数组?

Also how do you compare dates at these different levels to create an array of boolean indices?

推荐答案

您可以像这样通过布尔索引来过滤数据框:

You can filter your dataframe via boolean indexing like so:

df.loc[df['timeStamp'].dt.year == 2014]
df.loc[df['timeStamp'].dt.month == 5]
df.loc[df['timeStamp'].dt.second == 4]
df.loc[df['timeStamp'] == '2014-01-02']
df.loc[pd.to_datetime(df['timeStamp'].dt.date) == '2014-01-02']

...等等,依此类推.

... and so on and so forth.

这篇关于筛选并比较日期与 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆