我有这个表:
IdNum BeginDate Exitdate
-------------------------------------------------------------------------
123 2022-06-13 09:03 2022-06-13 22:12
633 2022-06-13 08:15 2022-06-13 13:09
389 2022-06-13 10:03 2022-06-13 18:12
665 2022-06-13 08:30 2022-06-13 10:12
我想获得一天中每15分钟的数据,以知道该人(IdNum)是否在此过程中。
例如:我想知道在18:00到18:15之间进程中有多少个IdNum。
根据上面的表格我应该得到:2
因为在当天的15分钟内只有IdNum 123和IdNum 389在处理。
我可以写一个函数或东西接收上面的表,并返回一个新表与96个新列(每15分钟一天)和每一行(IdNum)你得到True或False,如果他在那段时间的过程中?
的例子:
IdNum BeginDate Exitdate 00:00 - 00:15 18:00 - 18:15 etc etc..
----------------------------------------------------------------------------------------------
123 2022-06-13 09:03 2022-06-13 22:12 FALSE TRUE
633 2022-06-13 08:15 2022-06-13 13:09 FALSE FALSE
389 2022-06-13 10:03 2022-06-13 18:12 FALSE TRUE
665 2022-06-13 08:30 2022-06-13 10:12 FALSE FALSE
或者写一个接收3个变量的函数更容易:
一个表,一个开始时间(exmp: 18:00),一个结束时间(exmp: 18:15),它返回:2(在这两个时间之间存在的IdNum的数量)。
在Python上做什么更容易?这可能吗?你能给我指点一下在Python上用什么更好吗?是第一个还是第二个?
这是我的解决方案,您将有一个Dataframe, Id为idex,员工在这里工作的小时数为布尔值,如您在第一个示例中所示。
import pandas as pd
#Your initial Dataframe
df = pd.DataFrame([[123,"2022-06-13 09:03", "2022-06-13 22:12"],[633, "2022-06-13 08:15", "2022-06-13 13:09"]], columns=['IdNum', 'BeginDate', 'Exitdate'])
#The dictionnary where I'll stock the result
dico_res = {}
for i in range(df.shape[0]):
#I define a range of dates to know if your enter and exit is in the range
enter = pd.to_datetime(df.loc[i]["BeginDate"])
exit = pd.to_datetime(df.loc[i]["Exitdate"])
start = pd.to_datetime(enter.strftime("%d/%m/%Y"))
range_15_minutes = pd.date_range(start=start, end=end,freq="15min")
list_boolean, idx = [], []
for date in range(len(range_15_minutes)-1):
if enter >= range_15_minutes[date] and enter < range_15_minutes[date+1]:
list_boolean.append(True)
elif exit >= range_15_minutes[date] and exit < range_15_minutes[date+1]:
list_boolean.append(True)
elif exit < range_15_minutes[date] or enter > range_15_minutes[date]:
list_boolean.append(False)
else:
list_boolean.append(True)
idx.append(range_15_minutes[date].strftime("%H:%M") + "-" + range_15_minutes[date+1].strftime("%H:%M"))
dico_res[df.loc[i]["IdNum"]]=list_boolean
dataframe_solution = pd.DataFrame(dico_res, index=idx).T