Week of a month pandas

后端 未结 5 1535
孤街浪徒
孤街浪徒 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:39

    See this answer and decide which week of month you want.

    There's nothing built-in, so you'll need to calculate it with apply. For example, for an easy 'how many 7 day periods have passed' measure.

    data['wom'] = data[0].apply(lambda d: (d.day-1) // 7 + 1)
    

    For a more complicated (based on the calender), using the function from that answer.

    import datetime
    import calendar
    
    def week_of_month(tgtdate):
        tgtdate = tgtdate.to_datetime()
    
        days_this_month = calendar.mdays[tgtdate.month]
        for i in range(1, days_this_month):
            d = datetime.datetime(tgtdate.year, tgtdate.month, i)
            if d.day - d.weekday() > 0:
                startdate = d
                break
        # now we canuse the modulo 7 appraoch
        return (tgtdate - startdate).days //7 + 1
    
    data['calendar_wom'] = data[0].apply(week_of_month)
    

提交回复
热议问题