创建一个新列,并用熊猫范围之间的日期条件填充



我想创建一个新列,其中包含月份中的周数,即(第1周、第2周等(

我为每一周创建了一个日期范围,并使用if条件来填充新的列,但它不起作用,我不断收到错误

week1 = df[(df['start_time'] >= '2019-02-01') & (df['start_time'] <= '2019-02-07')]
week2 = df[(df['start_time'] >= '2019-02-08') & (df['start_time'] <= '2019-02-14')]
week3 = df[(df['start_time'] >= '2019-02-15') & (df['start_time'] <= '2019-02-21')]
week4 = df[(df['start_time'] >= '2019-02-22') & (df['start_time'] <= '2019-02-28')]
if df['start_time'] == week1:
df['trip_week'] = 'Week 1'

elif df['start_time'] == week2:
df['trip_week'] = 'Week 2'

elif df['start_time'] == week3:
df['trip_week'] = 'Week 3'

else:
df['trip_week'] = 'Week 4'
start_time
2019-02-02
2019-02-11
2019-02-22
2019-02-03
2019-02-27
2019-02-14
2019-02-17
2019-02-08
2019-02-14

这将起作用:

df["trip_week"] = "Week " + ((df["start_time"].dt.day // 7) + 1).astype(str)

添加一列,"Week "后跟一周的整数(将一个月的某一天除以7,再加1(。

相关内容

  • 没有找到相关文章

最新更新