我有一个数据框,其中记录了用户的每日出入情况,但是用户每天都在不同的时间到来,例如下面是输入的用户数据
Date UserID Intime Outtime
2018-06-29 73456 2018-06-29 07:30:54 2018-06-29 15:30:13
2018-06-28 73456 2018-06-28 08:29:23 2018-06-28 17:28:31
2018-06-27 73456 2018-06-27 11:26:02 2018-06-27 19:30:09
2018-06-26 73456 2018-06-26 14:20:42 2018-06-26 23:25:38
2018-06-25 73456 2018-06-25 07:31:19 2018-06-25 16:24:26
我需要保留该用户的每小时记录。所以在另一张纸上,我按小时列出日期和时间。我需要在用户字段中添加1
,例如用户所处的时间。例如输出数据。
Hours User
2018-06-29 0:00:00
2018-06-29 1:00:00
2018-06-29 2:00:00
2018-06-29 3:00:00
2018-06-29 4:00:00
2018-06-29 5:00:00
2018-06-29 6:00:00
2018-06-29 7:00:00 1
2018-06-29 8:00:00 1
2018-06-29 9:00:00 1
2018-06-29 10:00:00 1
2018-06-29 11:00:00 1
2018-06-29 12:00:00 1
2018-06-29 13:00:00 1
2018-06-29 14:00:00 1
2018-06-29 15:00:00 1
2018-06-29 16:00:00
2018-06-29 17:00:00
我能够创建小时列,但无法标记用户所在小时的出勤率。
任何帮助将不胜感激。谢谢 !
答案 0 :(得分:1)
尝试一下:
建立小时设置
s = pd.date_range(df1.index[0], df1.index[-1]+pd.DateOffset(1), freq='H')
idx = pd.period_range(df1.index[0], df1.index[-1]+pd.DateOffset(1), freq='H')
idx = idx[:-1]
在索引位于Intime
和Outtime
范围内时查找
sol = [int((s[i] >= df1.iloc[j,1] - pd.DateOffset(hours=1)) & (s[i] <= df1.iloc[j,2])) for j in range(len(df1)) for i in range(len(idx))]
使用numpy将列表重塑为更友好的格式
sol2 = np.array(sol)
sol3 = np.reshape(sol2, (s.shape[0]-1,len(df1)),order = 'F')
建立所需的系列
ans = pd.Series(np.amax(sol3, axis=1),idx.values)
显示结果
print(ans)
输出(最后一天):
2018-06-29 00:00 0
2018-06-29 01:00 0
2018-06-29 02:00 0
2018-06-29 03:00 0
2018-06-29 04:00 0
2018-06-29 05:00 0
2018-06-29 06:00 0
2018-06-29 07:00 1
2018-06-29 08:00 1
2018-06-29 09:00 1
2018-06-29 10:00 1
2018-06-29 11:00 1
2018-06-29 12:00 1
2018-06-29 13:00 1
2018-06-29 14:00 1
2018-06-29 15:00 1
2018-06-29 16:00 0
2018-06-29 17:00 0
2018-06-29 18:00 0
2018-06-29 19:00 0
2018-06-29 20:00 0
2018-06-29 21:00 0
答案 1 :(得分:0)
以下是我开发的解决方案。使用python 2.7
import pandas as pd
data = pd.read_excel("June_2018.xlsx", "sheetname")
df = pd.DataFrame(data) #created dataframe from excel data
my_df = pd.DataFrame({'Hours': pd.date_range("2018-06-01", "2018-06-30", freq='1H', closed='left')}) #created new dataframe with hourly frequency
df['Intime'] = df['Intime'].apply(lambda dt: dt.replace(minute=0, second=0)) #round off min and seconds to 0
df['Outtime'] = df['Outtime'].apply(lambda dt: dt.replace(minute=0, second=0)) #round off min and seconds to 0
for idx in set(df["UserID"]): #i have multiple userid so iterating over users
emp_data = df[df["UserID"] == idx] #filtered the table on user id basis
for item in set(emp_data["Date"].dt.date): #iterating over date
in_time = emp_data["Intime"][emp_data["Date"] == item] #finding intime
out_time = emp_data["Outtime"][emp_data["Date"] == item] #finding outtime
my_df.loc[(my_df["Hours"].values >= in_time.values) & (my_df["Hours"].values <= out_time.values), idx] = 1 #adding 1 where hourly value is in range
print my_df #printing the df