[英]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.between
和numpy.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.