在 python Pandas 中将对象转换为时间
Converting Object to Time in python Pandas
我有一个数据集,其中包含一个带有“时间”值的列,但它显示为对象,我想将它们转换为时间,这样我就可以执行一个 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
with 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
我有一个数据集,其中包含一个带有“时间”值的列,但它显示为对象,我想将它们转换为时间,这样我就可以执行一个 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
with 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