Home > Software design >  create and fill new column with date condition between a range pandas
create and fill new column with date condition between a range pandas

Time:09-27

I want to create a new column that will hold the week number in the month ie (week 1, week 2 etc...)

I created a date range for each weeks and used if condition to fill the new columns but it doesnt work I keep getting errors

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

Expected Output

start_time trip_week
2019-02-02 Week 1
2019-02-11 Week 2
2019-02-22 Week 4
2019-02-03 Week 1
2019-02-27 Week 4
2019-02-14 Week 2
2019-02-17 Week 3
2019-02-08 Week 2
2019-02-14 Week 2

CodePudding user response:

This will work:

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

Adds a column with "Week " followed by the integer of the week (dividing the day of the month by 7 - floor division - and adding 1).

  • Related