0

I'm working in machine learning regression problem where i predict sales value based on input features. In which date is one of the feature and i want to fetch month and week number from the date. Month gives in 1 to 12 that is okay. but for weeks i get between 1 to 52, which is also correct but i'm trying to get week number in range of 1 to 5, some months have 4 weeks and some have 5.

I have tried available methods for getting week number but it gives in range of 1 to 52 only. I can not just simply divide this by 4, otherwise no month will have 5 weeks.

this code gives output in range of 1 to 52 and i have also tried several other methods.

df['Week'] = df['Date'].dt.week

it should return like if a particular date is belong to fifth week of month than it should give week number 5.

kaushal
  • 11
  • 1
  • "i'm trying to get week number in range of 1 to 5, some months have weeks and some have 5" Huh? If a date is in the 49th week of the year, why would you expect to get anything other than 49? – DeepSpace Sep 03 '19 at 13:01
  • 1
    Are you trying to get week number relative to the month? Question is unclear. – MurrayW Sep 03 '19 at 13:03
  • @DeepSpace He wants the number of the week inside the month – Aryerez Sep 03 '19 at 13:05
  • @DeepSpace Any month with more than 28 days starts a 5th week – MurrayW Sep 03 '19 at 13:05
  • @kaushal -- see https://stackoverflow.com/questions/3806473/python-week-number-of-the-month – MurrayW Sep 03 '19 at 13:05
  • @Aryerez That gives you the modulo of the day of the week by 7 -- not sure how that tells you which week the date is in? E.g., both 2 % 7 and 23 % 7 == 2. – MurrayW Sep 03 '19 at 13:16
  • 1
    @MurrayW You are right. I meant using `// 7`, with `(month_day - 1) // 7 + 1` – Aryerez Sep 03 '19 at 13:19
  • @Aryerez thanks a lot for understanding query and your answer seems to be working in many case. – kaushal Sep 04 '19 at 06:44

1 Answers1

0

Week number refers to week of year in most contexts. Week of month is not a standard notion and is thus not implemented in pandas. You can implement it yourself. See e.g. this question on Stackoverflow.

ilmiacs
  • 2,566
  • 15
  • 20