Week of a month pandas

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)

Leave a Comment