vis vis - 1 month ago 9
Python Question

create a new column base on existing time column pyhton dataframe

I have to create a shift column based on existing time column

Ex I have data frame df1 with details

time
0 10:30
1 13:50
2 19:20
3 14:10


I need data frame which looks like below with shift condition 8:30 to 12:30 = shift 1 , 12:30 to 20:20 = shift 2 and 20:30 to 8:30 = shift 3

time shift
0 10:30 1
1 13:50 2
2 19:20 2
3 23:10 3

Answer

The following uses a dictionary of shifts that helps determine the shift associated with a given time:

import pandas as pd


df = pd.DataFrame({'time': ['00:00','08:29', '08:30', '08:31', '12:29', '12:30', '12:31', '20:29', '20:30', '20:31', '23:59', '10:30', '13:50', '19:20', '14:10', '23:10']})

# Convert the time column into datetime objects
df.time = pd.to_datetime(df.time).dt.time

# Set up a shifts dictionary
shifts = {('8:30', '12:30'): 1 , ('12:30', '20:30'): 2, ('20:30', '8:30'): 3}

# Convert the keys to datetime objects
shifts = {tuple(map(pd.to_datetime, k)):v for k,v in shifts.items()}

# Expand the datetime objects beyond one day if the second element occurred after the first element
shifts = {(k if k[0].time() < k[1].time() else (k[0],k[1]+pd.to_timedelta('1day'))):v for k,v in shifts.items()}

# Determine shift
def get_shift(time):
    try:
        return shifts.get([k for k in shifts if time in pd.date_range(*k, freq='60S', closed='left').time][0])
    except:
        return 'No Shift'

# Use .apply on the time column to get the shift column
df['shift'] = df.time.apply(get_shift)

print(df)

Outputs:

#         time  shift
# 0   00:00:00      3
# 1   08:29:00      3
# 2   08:30:00      1
# 3   08:31:00      1
# 4   12:29:00      1
# 5   12:30:00      2
# 6   12:31:00      2
# 7   20:29:00      2
# 8   20:30:00      3
# 9   20:31:00      3
# 10  23:59:00      3
# 11  10:30:00      1
# 12  13:50:00      2
# 13  19:20:00      2
# 14  14:10:00      2
# 15  23:10:00      3