converting a pandas date to week number

前端 未结 4 1635
轮回少年
轮回少年 2020-12-02 16:40

I would like to extract a week number from data in a pandas dataframe.

The date format is datetime64[ns]

I have normalized the date to remove the time from i

相关标签:
4条回答
  • 2020-12-02 17:19

    Pandas has its .dayofyear and .weekofyear functionality, which can be applied straight away to the output of pandas.to_datetime(df['column_name']), giving type "Timestamp" as the output.

    import pandas as pd
    df['formatted_date'] = pd.to_datetime(df['datetime'])
    df['day_of_year'] = df.formatted_date.apply(lambda x: x.dayofyear)
    df['week_of_year'] = df.formatted_date.apply(lambda x: x.weekofyear)
    
    0 讨论(0)
  • 2020-12-02 17:20

    Just access the dt week attribute:

    In [286]:
    df['Date'].dt.week
    
    Out[286]:
    0    25
    dtype: int64
    
    In [287]:
    df['Week_Number'] = df['Date'].dt.week
    df
    
    Out[287]:
            Date  Week_Number
    0 2015-06-17           25
    
    0 讨论(0)
  • 2020-12-02 17:20

    Here is another possibility using strftime. strftime.org is a good resource.

    df['Week_Number'] = df['Date'].dt.strftime('%U')
    

    '%U' represents the week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.

    If you have dates from multiple years, I recommend creating a Year-Week combination

    df['Year-Week'] = df['Date'].dt.strftime('%Y-%U')
    
    0 讨论(0)
  • 2020-12-02 17:23
    from datetime import date
    df_date = pd.DataFrame([date.today()],columns  = ['today'])
    print(df_date)
    #### Print Output ####
    #        today
    #0  2019-09-07
    df_date['weeknum'] = df_date.today.apply(lambda x:x.isocalendar()[1])
    print(df_date)
    #### Print Output ####
    #        today  weeknum
    #0  2019-09-07       36
    
    0 讨论(0)
提交回复
热议问题