如何使用 Pandas 按月、日、年过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27151546/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:42:54  来源:igfitidea点击:

How to filter by month, day, year with Pandas

pythonpandas

提问by user3445881

I create the DataFrame with:

我使用以下命令创建数据帧:

df = pandas.read_csv("data.csv", sep=';', parse_dates = 1, dayfirst = True)

df = pandas.read_csv("data.csv", sep=';', parse_dates = 1, dayfirst = True)

I then get the following results:

然后我得到以下结果:

                   Qty     System_created             Total
0                   2  2014-10-14 08:13:46.000         21.76  
1                   1  2014-10-14 08:13:46.000          4.16  
2                   2  2014-10-14 08:30:46.000         27.90  
3                   1  2014-10-14 08:30:46.000          4.95  
4                   1  2014-10-14 08:30:46.000          4.95  
5                   2  2014-11-05 11:15:47.000         21.76  
6                   1  2014-11-05 11:15:48.000          3.32  

But I do not know how to filter by month(or year, day, hour etc...). Something like df[df["System_created"].day]would be ideal. Is that possible?

但我不知道如何按月(或年、日、小时等)过滤。像df[df["System_created"].day]这样的东西是理想的。那可能吗?

回答by EdChum

So long as your pandas version is 0.15or higher then the following would work assuming your dtypeis already a datetime:

只要您的 Pandas 版本是0.15或更高,那么假设您dtype已经是日期时间,则以下内容将起作用:

In [167]:

df[df.System_created.dt.day == 5]
Out[167]:
       Qty      System_created  Total
index                                
5        2 2014-11-05 11:15:47  21.76
6        1 2014-11-05 11:15:48   3.32

So basically the dtattribute allows you to access the components of your datetime to perform the comparisons you desire for filtering

所以基本上该dt属性允许您访问日期时间的组件以执行您想要过滤的比较