繁体   English   中英

将Object转换为python中的时间 Pandas

[英]Converting Object to Time in python Pandas

我有一个包含带有“时间”值的列的数据集,但它显示为 object,我想将它们转换为时间,以便我可以执行 for 循环以查看时间是否介于两次之间。

for i in df['Time']:
    if i >= dt.time(21,0,0) and i <= dt.time(7, 30,0) or i >= dt.time(3,0,0) and i <= dt.time(10,0,0) or i >= dt.time(10,30,0) and i <= dt.time(14,0,0):
        df['In/Out'] = 'In'
    else:
        df['In/Out'] = 'Out'

如果时间介于两次之间,我希望代码将新列中的值设置为“In”。 第一次是(21:00)和(07:30)第二次是(03:00)和(10:00)第三次是(10:30)和(14:00)

如果时间不在这些范围内,则应将新列中的值设置为“Out”。

你可以简化:

(21:00) & (07:30) the second are (03:00) & (10:00) 

到:

(21:00) & (10:00) 

所以解决方案是使用Series.betweennumpy.where

df=pd.DataFrame({'Time':['0:01:00','8:01:00','2021-08-13 10:19:10','12:01:00',
                        '14:01:00','18:01:01','23:01:00']})

df['Time'] = pd.to_datetime(df['Time']).dt.time


m = (df['Time'].between(dt.time(21,0,0), dt.time(23,23,23)) | 
      df['Time'].between(dt.time(0,0,0), dt.time(10,0,0)) | 
      df['Time'].between(dt.time(10,30,0), dt.time(14, 0,0)))

df['In/Out'] = np.where(m, 'In','Out')
print (df)
       Time In/Out
0  00:01:00     In
1  08:01:00     In
2  10:19:10    Out
3  12:01:00     In
4  14:01:00    Out
5  18:01:01    Out
6  23:01:00     In

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM