Ryan
Ryan

Reputation: 2886

Python filter rows in dataframe by date

I have a dataframe in the following format:

month     count
2015/01   100
2015/02   200
2015/03   300
...

And want to get a new dataframe which contains month greater than a month, e.g.. 2015/03.

I tried to use the following code:

sdf = df.loc[datetime.strptime(df['month'], '%Y-%m')>=datetime.date(2015,9,1,0,0,0)]

I'm new to Python. Really appreciate it if some one can help.

Upvotes: 0

Views: 1593

Answers (1)

akuiper
akuiper

Reputation: 214957

If you want to get rows which have months larger than 2015/02 for instance, use pd.to_datetime instead of datetime.strptime since the former is vectorized and can accept a Series object as parameter (assuming you are using pandas):

import pandas as pd
df[pd.to_datetime(df.month) >= pd.to_datetime("2015/02")]

#     month count
#1  2015/02   200
#2  2015/03   300

Upvotes: 1

Related Questions