在Python的数据框上使用时间戳值的布尔过滤器 [英] Boolean filter using a timestamp value on a dataframe in Python
本文介绍了在Python的数据框上使用时间戳值的布尔过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从.csv
文档创建的数据框.由于其中一列包含日期,因此我将熊猫read_csv
与parse_dates
一起使用:
I have a dataframe created from a .csv
document. Since one of the columns has dates, I have used pandas read_csv
with parse_dates
:
df = pd.read_csv('CSVdata.csv', encoding = "ISO-8859-1", parse_dates=['Dates_column'])
日期范围是2012年至2016年.我想创建一个子数据框,其中仅包含2014年的行.
The dates range from 2012 to 2016. I want to crate a sub-dataframe, containing only the rows from 2014.
我设法做到这一点的唯一方法是使用两个后续的布尔过滤器:
The only way I have managed to do this, is with two subsequent Boolean filters:
df_a = df[df.Dates_column>pd.Timestamp('2014')] # To create a dataframe from 01/Jan/2014 onwards.
df = df_a[df_a.Dates_column<pd.Timestamp('2015')] # To remove all the values after 01/jan/2015
有没有一种方法可以一步一步地更有效地进行此操作?
Is there a way of doing this in one step, more efficiently?
非常感谢!
推荐答案
您可以使用 dt
访问器:
You can use the dt
accessor:
df = df[df.Dates_column.dt.year == 2014]
这篇关于在Python的数据框上使用时间戳值的布尔过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文