Skip to main content
 首页 » 编程设计

python之如何在 python 中知道时间间隔内是否包含具有日期格式的数据框(矢量化)

2024年10月17日8zfyouxi

我有以下数据框:

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 

非常感谢你提前

请您参考如下方法:

我想你可以使用 to_datetime首先创建mask,由astype转换为int ,但如果 minutes 和 seconds 为 0,则此解决方案无效:

df.arrivalTime = pd.to_datetime(df.arrivalTime)  
h = df.arrivalTime.dt.hour   
mask = (h > 15) & (h < 20) 
df['result'] = mask.astype(int) 
 
print (df) 
   index         arrivalTime  result 
0      0 2016-01-11 06:53:15       0 
1      1 2016-01-11 06:55:25       0 
2      2 2016-03-11 16:57:10       1 
3      3 2016-03-11 16:57:30       1 
4      4 2016-04-11 18:58:10       1 
5      5 2016-06-11 19:58:35       1 
6      6 2016-08-11 20:00:05       0 

与 dt.time 类似的解决方案- 提取时间然后比较它们:

df.arrivalTime = pd.to_datetime(df.arrivalTime)    
 
h1 = dt.datetime.strptime('16:00:00', '%H:%M:%S').time() 
h2 = dt.datetime.strptime('20:00:00', '%H:%M:%S').time() 
times = df.arrivalTime.dt.time 
mask = (times >= h1) & (times <= h2) 
df['result'] = mask.astype(int) 
print (df) 
          arrivalTime  result 
0 2016-01-11 06:53:15       0 
1 2016-01-11 06:55:25       0 
2 2016-03-11 16:57:10       1 
3 2016-03-11 16:57:30       1 
4 2016-04-11 18:58:10       1 
5 2016-06-11 19:58:35       1 
6 2016-08-11 20:00:05       0 

另一种解决方案 between_time仅适用于 DatetimeIndex - 输出分配给 result 列并针对 notnull 进行测试:

df.arrivalTime = pd.to_datetime(df.arrivalTime)  
df['result'] = 1 
df.set_index('arrivalTime', inplace=True) 
df['result'] = df.between_time('16:00', '20:00') 
df['result'] = df['result'].notnull().astype(int) 
print (df) 
                     result 
arrivalTime                 
2016-01-11 06:53:15       0 
2016-01-11 06:55:25       0 
2016-03-11 16:57:10       1 
2016-03-11 16:57:30       1 
2016-04-11 18:58:10       1 
2016-06-11 19:58:35       1 
2016-08-11 20:00:05       0