【发布时间】:2016-11-23 15:14:33
【问题描述】:
我有以下数据框:
index arrivalTime
0 01/11/2016 06:53:15
1 01/11/2016 06:55:25
2 03/11/2016 16:57:10
3 03/11/2016 16:57:30
4 04/11/2016 18:58:10
5 06/11/2016 19:58:35
6 08/11/2016 20:00:05
我需要知道不同日期 16:00:00 到 20:00:00 之间的行。我举个例子结果:
index arrivalTime result
0 01/11/2016 06:53:15 0
1 01/11/2016 06:55:25 0
2 03/11/2016 16:57:10 1
3 03/11/2016 16:57:30 1
4 04/11/2016 18:58:10 1
5 06/11/2016 19:58:35 1
6 08/11/2016 20:00:05 0
我使用 apply 函数和一个嵌套函数得到了上述结果,但速度很慢,我想“矢量化”,但我做不到。
def function_time(df):
df['hora_lle'] = df['arrivalTime'].map(lambda x: x[-8:])
def class(hora_lle):
x = dt.datetime.strptime(hora_lle, '%H:%M:%S').time()
h1 = dt.datetime.strptime('16:00:00', '%H:%M:%S').time()
h2 = dt.datetime.strptime('20:00:00', '%H:%M:%S').time()
if x < h1:
return 0
elif h1 <= x < h2:
return 1
elif h2 <= x:
return 0
df['seg'] = df['hora_sal'].apply(class)
return df
非常感谢您
【问题讨论】:
标签: python pandas time dataframe vectorization