Luc
Luc

Reputation: 747

Convert day of the month to week

Expected Output: df
year  | month   | day | week 
2019  |   3     | 1   | 1
2017  |  12     | 15  | 2
2016  |   9     | 28  | 4
2020  |   4     | 22  | 3

I would like to convert the day (1 to 31) to week. For example, if the day is 1-8, it is week 1. If the day is 9-16, it is week 2, and so on.

The following code however returns an invalid syntax.

for row in df:
    if df['day'] <= 8:
        df['Week'] = 1 
        elif df['day'] <= 16:
        df['Week'] = 2 
        elif df['day'] <= 24:
        df['Week'] = 3
    else:
        df['Week'] = 4

It is even better if it is more accurate, as each month has different starting first day of the week, but I have no idea how to do so.

Upvotes: 1

Views: 52

Answers (1)

jezrael
jezrael

Reputation: 862581

If need count week only by days use integers division by 8 and add 1:

df['week1'] = df['day'] // 8 + 1
print (df)
   year  month  day  week  week1
0  2019      3    1     1      1
1  2017     12   15     2      2
2  2016      9   28     4      4
3  2020      4   22     3      3

If need weeks by datetimes first use to_datetime and then Series.dt.weekofyear:

df['week2'] = pd.to_datetime(df[['day', 'month','year']]).dt.weekofyear
print (df)
   year  month  day  week  week2
0  2019      3    1     1      9
1  2017     12   15     2     50
2  2016      9   28     4     39
3  2020      4   22     3     17

Upvotes: 2

Related Questions