How to filter a date data frame in a specific month / day?

So my code is as follows:

df['Dates'][df['Dates'].index.month == 11] 

I did a test to check if I can filter the months, so it only shows November dates, but that didn't work. This gives me the following error: AttributeError: the "Int64Index" object does not have the month attribute.

If i do

 print type(df['Dates'][0]) 

then I get the class 'pandas.tslib.Timestamp', which makes me think that the types of objects stored in the data frame are Timestamp objects. (I'm not sure where "Int64Index" comes from ... for the error before)

What I want to do is: the dataframe column contains dates from the beginning of 2000 to the present in the following format: dd / mm / yyyy. I want to filter dates only from November 15 to March 15, regardless of YEAR. What is the easiest way to do this?

Thanks.

Here df ['Dates'] (with indexes):

 0 2006-01-01 1 2006-01-02 2 2006-01-03 3 2006-01-04 4 2006-01-05 5 2006-01-06 6 2006-01-07 7 2006-01-08 8 2006-01-09 9 2006-01-10 10 2006-01-11 11 2006-01-12 12 2006-01-13 13 2006-01-14 14 2006-01-15 ... 
+5
source share
1 answer

Match anonymous function to calculate the month for a series and compare it with 11 for a new one. This will give you a logical mask. You can then use this mask to filter your frame.

 nov_mask = df['Dates'].map(lambda x: x.month) == 11 df[nov_mask] 

I don’t think there is a direct way to filter how you want to ignore the year, so try this.

 nov_mar_series = pd.Series(pd.date_range("2013-11-15", "2014-03-15")) #create timestamp without year nov_mar_no_year = nov_mar_series.map(lambda x: x.strftime("%m-%d")) #add a yearless timestamp to the dataframe df["no_year"] = df['Date'].map(lambda x: x.strftime("%m-%d")) no_year_mask = df['no_year'].isin(nov_mar_no_year) df[no_year_mask] 
+10
source

Source: https://habr.com/ru/post/1202698/


All Articles