[英]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.我想将天(1 到 31)转换为周。 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.
例如,如果天是 1-8,则是第 1 周。如果天是 9-16,则是第 2 周,依此类推。
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
:如果只需要按天计算
week
数,请使用整数除以8
并加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
:如果需要按日期时间按周首先使用
to_datetime
然后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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.