根据日期时间列对 pandas 数据框进行切片 [英] Slice pandas dataframe based on datetime column

查看:87
本文介绍了根据日期时间列对 pandas 数据框进行切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个pandas数据框,其中的一列为datatime,如下所示:

I have a pandas dataframe with a column as datatime that looks like:

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

我想通过消除2009年之前的所有行来对数据帧进行切片

I'd like to slice the dataframe by eliminating all rows before 2009

推荐答案

您可以使用简单的字符串比较将值与年份字符串进行比较:

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

或使用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

这篇关于根据日期时间列对 pandas 数据框进行切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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