答案 0 :(得分:1)
我相信您需要map
和timedelta_range
和zip
创建的字典,因为相同类型的数据是必需的,请转换列to_timedelta
:
df = pd.DataFrame({'Time':['00:00:00','00:30:00','01:00:00','08:00:00']})
print (type(df['Time'].iat[0]))
<class 'str'>
d = dict(zip(pd.timedelta_range('00:00:00', '23:30:00', freq='30T'), range(1, 49)))
df['EncodedTime'] = pd.to_timedelta(df['Time']).map(d)
print (df)
Time EncodedTime
0 00:00:00 1
1 00:30:00 2
2 01:00:00 3
3 08:00:00 17
date_range
与DatetimeIndex.strftime
创建的类似解决方案:
d = dict(zip(pd.date_range('00:00:00', '23:30:00', freq='30T').strftime('%H:%M:%S'),
range(1, 49)))
df['EncodedTime'] = df['Time'].map(d)
与时俱进的解决方案:
df = pd.DataFrame({'Time':pd.to_datetime(['00:00:00','00:30:00','01:00:00','08:00:00']).time})
print (type(df['Time'].iat[0]))
<class 'datetime.time'>
d = dict(zip(pd.date_range('00:00:00', '23:30:00', freq='30T').time, range(1, 49)))
df['EncodedTime'] = df['Time'].map(d)