pandas 根据日期时间列切片熊猫数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31878699/
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 23:45:17 来源:igfitidea点击:
Slice pandas dataframe based on datetime column
提问by Blue Moon
I have a pandas dataframe with a column as datatime that looks like:
我有一个 Pandas 数据框,其中有一列作为数据时间,如下所示:
data.ts_placed
Out[68]:
1 2008-02-22 15:30:40
2 2008-03-20 16:56:00
3 2008-06-14 21:26:02
4 2008-06-16 10:26:02
5 2008-06-23 20:41:03
6 2008-07-17 08:02:00
7 2008-10-13 12:47:05
8 2008-11-14 09:20:33
9 2009-02-23 11:24:18
10 2009-03-02 10:29:19
I'd like to slice the dataframe by eliminating all rows before 2009
我想通过消除 2009 年之前的所有行来切片数据帧
回答by EdChum
You can use a simple string comparison to compare the values against a year string:
您可以使用简单的字符串比较将值与年份字符串进行比较:
In [63]:
df.loc[df['date'] >= '2009']
Out[63]:
date
index
9 2009-02-23 11:24:18
10 2009-03-02 10:29:19
Or use the dtattribute to access the year:
或者使用dt属性来访问年份:
In [64]:
df.loc[df['date'].dt.year >= 2009]
Out[64]:
date
index
9 2009-02-23 11:24:18
10 2009-03-02 10:29:19

