我必须基于现有时间列创建一个班次列。
例如,我有一个包含详细信息的数据框df1:
time
0 10:30
1 13:50
2 19:20
3 14:10
我需要一个带有移位条件的数据框,如下所示:
time shift 0 10:30 1 1 13:50 2 2 19:20 2 3 23:10 3
以下内容使用了班次字典,可帮助确定与给定时间相关的班次:
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)
输出:
# 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句