How to filter a dataframe of dates by a particular month/day?

前端 未结 3 1097
天涯浪人
天涯浪人 2020-11-30 07:37

So my code is as follows:

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

I was doing a test to see if I could filter the months so it only

3条回答
  •  清歌不尽
    2020-11-30 08:24

    Map an anonymous function to calculate the month on to the series and compare it to 11 for nov. That will give you a boolean mask. You can then use that mask to filter your dataframe.

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

    I don't think there is straight forward way to filter the way you want ignoring 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]
    

提交回复
热议问题