如何根据熊猫的条件过滤时间戳

时间:2018-08-04 13:22:59

标签: python-3.x pandas

我想根据条件过滤熊猫数据框中的时间戳列。

Input

Pickup date/time      
07/05/2017 09:28:00                     
14/05/2017 15:32:20                     
15/05/2018 17:00:00                    
15/05/2018 11:20:09                    
23/06/2018 22:00:00                   
29/06/2018 16:10:02  

我想根据条件时间戳大于16:00:00在数据框中添加另一列

Expected Output

   Pickup date/time      Pickup  
    07/05/2017 09:28:00      On-time                 
    14/05/2017 15:32:20      On-time             
    15/05/2018 17:00:00      Delayed              
    15/05/2018 11:20:09      On-time              
    23/06/2018 22:00:00      Delayed           
    29/06/2018 16:10:02      Delayed 

1 个答案:

答案 0 :(得分:4)

使用np.where

df['new'] = np.where(df.p.dt.hour > 16, 'Delayed', 'On-time')

df['new'] = np.where(df.p.dt.time > datetime.time(16, 0, 0), 'Delayed', 'On-time')

输出

    p                  new
0   2017-07-05 09:28:00 On-time
1   2017-05-14 15:32:20 On-time
2   2018-05-15 17:00:00 Delayed
3   2018-05-15 11:20:09 On-time
4   2018-06-23 22:00:00 Delayed
5   2018-06-29 16:10:02 Delayed