Filtering Pandas DataFrames on dates

前端 未结 12 1255
时光取名叫无心
时光取名叫无心 2020-11-22 16:15

I have a Pandas DataFrame with a \'date\' column. Now I need to filter out all rows in the DataFrame that have dates outside of the next two months. Essentially, I only need

12条回答
  •  爱一瞬间的悲伤
    2020-11-22 16:49

    The shortest way to filter your dataframe by date: Lets suppose your date column is type of datetime64[ns]

    # filter by single day
    df = df[df['date'].dt.strftime('%Y-%m-%d') == '2014-01-01']
    
    # filter by single month
    df = df[df['date'].dt.strftime('%Y-%m') == '2014-01']
    
    # filter by single year
    df = df[df['date'].dt.strftime('%Y') == '2014']
    

提交回复
热议问题