[英]How to calculate the average hours between two different times in Python
[英]calculate if date value occurs between two different times python pandas
我正在尝试创建一个新列,以确定行值是否在“营业时间之间”。 为此,我尝试使用时间间隔功能。 如果有更简单的方法,我不需要使用它。
我有一个数据框 ,其中包含“ Date” , “ StartHour” , “ End Hour”的列 。
题:
我想给一个“真”或“假”,如果在“ 日期 ”一栏中的时间是“StartHour”之间'EndHour的时间。
import pandas as pd
import numpy as np
#create dataframe with dates
d = {'Date': ['2016-11-17 05:01:45','2011-01-04 16:34:00','2011-01-05 09:25:45',
'2011-01-10 12:00:45','2011-01-14 07:05:45','2011-01-15 10:19:00',
'2011-01-17 13:59:45','2011-01-19 18:39:45','2011-01-22 06:19:45'],
'StartHour': ['16:00','16:00','16:00','16:00','16:00','16:00','16:00','16:00','16:00'],
'EndHour': ['10:00','10:00','10:00','10:00','10:00','10:00','10:00','10:00','10:00'],
'Station_ID': ['A','A','A','A','B','B','B','B','B']}
df = pd.DataFrame(data=d)
#convert date column to datetime
df['Date'] = df['Date'].values.astype('datetime64[ns]')
#************************
# set index to Date (need for 'between_time')
df = df.set_index('Date')
# run calculation for between time
df['between_business_hours'] = df.index.isin(df.between_time('16:00', '10:00', include_start=True, include_end=True).index)
df
我已经使用between_time函数计算了一个列,但这只允许我使用硬编码值作为开始时间和结束时间。 我想使用“ StartTime”和“ EndTime”列中的值。 我可能通过使用between_time函数使此操作比需要的更加困难。
我希望输出看起来像这样。
EndHour StartHour Station_ID between_business_hours
Date
2016-11-17 05:01:45 10:00 16:00 A True
2011-01-04 16:34:00 10:00 16:00 A True
2011-01-05 09:25:45 10:00 16:00 A True
2011-01-10 12:00:45 10:00 16:00 A False
2011-01-14 07:05:45 10:00 16:00 B True
2011-01-15 10:19:00 10:00 16:00 B False
2011-01-17 13:59:45 10:00 16:00 B False
2011-01-19 18:39:45 10:00 16:00 B True
2011-01-22 06:19:45 10:00 16:00 B True
任何帮助表示赞赏
您不需要设置index
df.Date.dt.strftime('%H:%M').between(df.StartHour,df.EndHour)
Out[297]:
0 False
1 True
2 True
3 True
4 False
5 True
6 True
7 True
8 False
dtype: bool
更新
l=[df.loc[[y],:].index.indexer_between_time(df.loc[y,'StartHour'],df.loc[y,'EndHour'])==0 for y in df.index]
df['New']=l
df.New=df.New.str[0].fillna(False)
df
EndHour StartHour Station_ID New
Date
2016-11-17 05:01:45 10:00 16:00 A True
2011-01-04 16:34:00 10:00 16:00 A True
2011-01-05 09:25:45 10:00 16:00 A True
2011-01-10 12:00:45 10:00 16:00 A False
2011-01-14 07:05:45 10:00 16:00 B True
2011-01-15 10:19:00 10:00 16:00 B False
2011-01-17 13:59:45 10:00 16:00 B False
2011-01-19 18:39:45 10:00 16:00 B True
2011-01-22 06:19:45 10:00 16:00 B True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.