简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM