2

I have a list of dates in a DF that have been converted to a YYYY-MM format and need to select a range. This is what I'm trying:

#create dataframe    
data = ['2016-01','2016-02','2016-09','2016-10','2016-11','2017-04','2017-05','2017-06','2017-07','2017-08']
df = pd.DataFrame(data, columns = {'date'})

#lookup range
df[df["date"].isin(pd.date_range('2016-01', '2016-06'))]

It doesn't seem to be working because the date column is no longer a datetime column. The format has to be in YYYY-MM. So I guess the question is, how can I make a datetime column with YYYY-MM? Can someone please help? Thanks.

1 Answer 1

3

You do not need an actual datetime-type column or query values for this to work. Keep it simple:

df[df.date.between('2016-01', '2016-06')]

That gives:

      date
0  2016-01
1  2016-02

It works because ISO 8601 date strings can be sorted as if they were plain strings. '2016-06' comes after '2016-05' and so on.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.