Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Week of a month pandas

Tags:

python

pandas

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 interested in the last week of the month.

data = pd.DataFrame(pd.date_range(' 1/ 1/ 2000', periods = 100, freq ='D'))

0  2000-01-01
1  2000-01-02
2  2000-01-03
3  2000-01-04
4  2000-01-05
5  2000-01-06
6  2000-01-07
like image 905
user3816493 Avatar asked Aug 11 '14 17:08

user3816493


People also ask

How many days are in a panda month?

As we can see in the output, the Timestamp. days_in_month attribute has returned 28 indicating that there are 28 days in the month of the given Timestamp object.

Where is the week number in Pandas?

The isocalendar() function in Pandas returns the ISO year, week number, and weekday from a Timestamp object (an equivalent of Python's datetime object).

How do you get the month difference in Pandas?

Use df. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.


1 Answers

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)
like image 173
chrisb Avatar answered Sep 22 '22 12:09

chrisb