How to make the condition or when selecting dates

Viewed 49

I have a dataframe where index is a date. I want to select the rows, which belong to the dates between '01-01-2016' and '01-03-2016' or between dates '15-12-2016' and '01-01-2017'.

To do the first part I use the code

mask = ((f11.index > datetime.strptime('01-01-2016','%d-%m-%Y')) & (f11.index <= datetime.strptime('01-03-2016','%d-%m-%Y')))

and later call the function

f11 = f11.loc[mask]

Now I cant do it so that I get both conditions, I tried to put a condition with or but it does not work.

mask = (((f11.index > datetime.strptime('01-01-2016','%d-%m-%Y')) & (f11.index <= datetime.strptime('01-03-2016','%d-%m-%Y')) or
            (f11.index > datetime.strptime('15-12-2016', '%d-%m-%Y')) & (
                        f11.index <= datetime.strptime('01-01-2017', '%d-%m-%Y')) )) 
1 Answers

Use | instead of or. Also, you can compare string with datetime type in pandas:

mask1 = (f11.index > '01-01-2016') & (f11.index <= '03-01-2016')
mask2 = (f11.index > '12-15-2016') & (f11.index <= '01-01-2017')

mask = mask1 | mask2
Related