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

前端 未结 3 1080
天涯浪人
天涯浪人 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:21

    Using pd.to_datetime & dt accessor

    The accepted answer is not the "pandas" way to approach this problem.

    To select only rows with month 11, use the dt accessor:

    # df['Date'] = pd.to_datetime(df['Date']) -- if column is not datetime yet
    df = df[df['Date'].dt.month == 11]
    

    Same works for days or years, where you can substitute dt.month with dt.day or dt.year

    Besides that, there are many more, here are a few:

    • dt.quarter
    • dt.week
    • dt.weekday
    • dt.day_name
    • dt.is_month_end
    • dt.is_month_start
    • dt.is_year_end
    • dt.is_year_start

    For a complete list see the documentation

提交回复
热议问题