Week of a month pandas

后端 未结 5 1533
孤街浪徒
孤街浪徒 2020-12-16 01:21

I\'m trying to get week on a month, some months might have four weeks some might have five. For each date i would like to know to which week does it belongs to. I\'m mostly

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 01:35

    I've used the code below when dealing with dataframes that have a datetime index.

    import pandas as pd
    import math
    
    def add_week_of_month(df):
        df['week_in_month'] = pd.to_numeric(df.index.day/7)
        df['week_in_month'] = df['week_in_month'].apply(lambda x: math.ceil(x))
        return df
    

    If you run this example:

    df = test = pd.DataFrame({'count':['a','b','c','d','e']},
                         index = ['2018-01-01', '2018-01-08','2018-01-31','2018-02-01','2018-02-28'])
    df.index = pd.to_datetime(df.index)
    

    you should get the following dataframe

                   count  week_in_month
    
    2018-01-01     a              1
    2018-01-08     b              2
    2018-01-31     c              5
    2018-02-01     d              1
    2018-02-28     e              4
    

提交回复
热议问题