Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

python - Pandas filter dataframe rows with a specific year

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.

Is there some way like this?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...