pandas 过滤特定年份的数据框行 [英] Pandas filter dataframe rows with a specific year

查看:63
本文介绍了 pandas 过滤特定年份的数据框行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框df,它有一个Date列.我想创建两个新的数据框.一个包含年份等于some_yeardf中所有行,另一个包含年份不等于some_yeardf所有行的数据框.我知道您可以做df.ix['2000-1-1' : '2001-1-1'],但是为了获得2000年以外的所有行,需要创建2个额外的数据帧,然后进行串联/联接.

I have a dataframe df and it has a Date column. I want to create two new data frames. One which contains all of the rows from df where the year equals some_year and another data frame which contains all of the rows of df where the year does not equal some_year. I know you can do df.ix['2000-1-1' : '2001-1-1'] but in order to get all of the rows which are not in 2000 requires creating 2 extra data frames and then concatenating/joining them.

有这样的方法吗?

include = df[df.Date.year == year]
exclude = df[df['Date'].year != year]

此代码不起作用,但是有任何类似的方式吗?

This code doesn't work, but is there any similar sort of way?

推荐答案

您可以使用日期时间访问权限.

You can use datetime accesor.

import datetime as dt
df['Date'] = pd.to_datetime(df['Date'])

include = df[df['Date'].dt.year == year]
exclude = df[df['Date'].dt.year != year]

这篇关于 pandas 过滤特定年份的数据框行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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