python中的数据透视
我在计算员工的出勤率,这是样本表python中的数据透视,python,pandas,date,dataframe,pivot,Python,Pandas,Date,Dataframe,Pivot,我在计算员工的出勤率,这是样本表 df = pd.DataFrame({ 'E_ID': [1001, 1001, 1001, 1002, 1002, 1002, 1002], 'Date': [ '28-07-2019 08:27:00', '28-07-2019 18:10:00', '29-07-2019 08:10:00', '28-07-2019 08:07:00', '29-07-2019
df = pd.DataFrame({
'E_ID': [1001, 1001, 1001, 1002, 1002, 1002, 1002],
'Date': [
'28-07-2019 08:27:00',
'28-07-2019 18:10:00',
'29-07-2019 08:10:00',
'28-07-2019 08:07:00',
'29-07-2019 08:10:10',
'29-07-2019 08:10:17',
'29-07-2019 17:50:00'
]
})
我正试图从df
的Date
列计算每天的进出时间
此外,每天可能有一个条目,可以作为打卡时间处理
时间将是第一次打孔和
下班时间将是最后一次打卡
我希望输出像这样的东西,或者类似的东西
E_ID OfficePunch In Punch Out Punch
1001 28-08-2019 28-07-2019 08:27 28-07-2019 18:10
1001 29-08-2019 29-07-2019 08:10 29-07-2019 08:10
1002 28-08-2019 28-07-2019 08:07 28-07-2019 08:07
1002 29-08-2019 29-07-2019 08:10 29-07-2019 17:50
有什么方法可以做到这一点吗?对于输出
OfficePunch
列中的python对象日期,请使用“按第一个值和最后一个值聚合”:
df['Date'] = pd.to_datetime(df['Date'])
df1 = (df.groupby(['E_ID', df['Date'].dt.date.rename('OfficePunch')])['Date']
.agg([('In Punch','first'),('Out Punch','last')])
.reset_index())
print (df1)
E_ID OfficePunch In Punch Out Punch
0 1001 2019-07-28 2019-07-28 08:27:00 2019-07-28 18:10:00
1 1001 2019-07-29 2019-07-29 08:10:00 2019-07-29 08:10:00
2 1002 2019-07-28 2019-07-28 08:07:00 2019-07-28 08:07:00
3 1002 2019-07-29 2019-07-29 08:10:10 2019-07-29 17:50:00
print (df1.dtypes)
E_ID int64
OfficePunch object
In Punch datetime64[ns]
Out Punch datetime64[ns]
dtype: object
如果需要在OfficePunch
列中使用日期时间,请使用:
df['Date'] = pd.to_datetime(df['Date'])
df1 = (df.groupby(['E_ID', df['Date'].dt.floor('d').rename('OfficePunch')])['Date']
.agg([('In Punch','first'),('Out Punch','last')])
.reset_index())
print (df1)
E_ID OfficePunch In Punch Out Punch
0 1001 2019-07-28 2019-07-28 08:27:00 2019-07-28 18:10:00
1 1001 2019-07-29 2019-07-29 08:10:00 2019-07-29 08:10:00
2 1002 2019-07-28 2019-07-28 08:07:00 2019-07-28 08:07:00
3 1002 2019-07-29 2019-07-29 08:10:10 2019-07-29 17:50:00
print (df1.dtypes)
E_ID int64
OfficePunch datetime64[ns]
In Punch datetime64[ns]
Out Punch datetime64[ns]
dtype: object