Expected Output: df
year | month | day | week
2019 | 3 | 1 | 1
2017 | 12 | 15 | 2
2016 | 9 | 28 | 4
2020 | 4 | 22 | 3
我想将日期(1到31)转换为星期。 例如,如果一天是1-8,则是第1周。 如果一天是9到16,则是第2周,依此类推。
但是,以下代码返回无效的语法。
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
如果它更准确,那就更好了,因为每个月的第一天的开始时间都不一样,但是我不知道该怎么做。
答案 0 :(得分:2)
如果仅需按天数计算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
如果在日期时间之前需要几周,请先使用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