将日期拆分为该月的第 1、2、3、4 周

Split the date into 1st, 2nd, 3rd, 4th week of the month

我有一个日期数据框:

  id|date
  13|2017-01-31
  12|2016-12-07
  11|2013-03-19

我想将日期分类为天气,即每月的第一周、第二周、第三周或第四周。

我正在使用这个功能:


calendar.setfirstweekday(calendar.SUNDAY)

def get_week_of_month(dt):
    year  = dt.year
    month = dt.month
    day   = dt.day
    x = np.array(calendar.monthcalendar(year, month))
    week_of_month = np.where(x==day)[0][0] + 1
    return(week_of_month)

df['week_month'] = df['date'].apply(get_week_of_month)

但是我可能有 6 周而不是 4 周。请帮助

像这样:

In [1036]: df['date']= pd.to_datetime(df['date'])

In [1044]: df['week_of_month'] = ((df['date'].dt.day-1)//7)+1

In [1045]: df 
Out[1045]: 
   id       date  week_of_month
0  13 2017-01-31              5
1  12 2016-12-07              1
2  11 2013-03-19              3