在Pandas身上表演精彩绝伦的表演

2024-10-01 09:23:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,列出了员工和他们完成某些操作的时间戳。它分为三列:雇员、日期、小时。在

我想计算每小时活跃的员工人数。在excel中,我将通过添加第四列EmpFactor来完成此操作,在该列中我执行COUNTIFS操作:

=1/COUNTIFS(Name range;Name;Date range;Date;Hour range;Hour)

随后,我可以通过对EmpFactor列执行SUMIF来计算在职员工的数量。在

我尝试使用pandas编写EmpFactor列:

^{pr2}$

但这不起作用。我广泛地搜索了许多关于SO的话题,但还没有找到合适的答案。在


Tags: 数据namedate时间员工rangeexcel小时
2条回答

假设您有这样的数据帧结构:

import pandas as pd
import numpy as np
df = pd.DataFrame([['Alice', '2012-03-05', 23], 
                   ['Fred',  '2012-03-05', 23], 
                   ['Bob',   '2012-12-12', 00]], 
                  columns=('Employee', 'Date', 'Time'))

# Here you have:
    Employee        Date  Time
0      Alice  2012-03-05    23
1       Fred  2012-03-05    23
2        Bob  2012-12-12     0

# convert to a date
df['DateTime']=pd.to_datetime(df['Date'])
# make it index
df2=df.set_index('DateTime')
# group by date and time
g = df2.groupby([pd.TimeGrouper('D'), 'Time'])
# get counts:
print(g.count())

#Here you have:
                     Employee  Date
DateTime      Time
2012-03-05     23           2     2
2012-12-12      0           1     1


# to get inverted values:
print(1/g.count())

                   Employee  Date
DateTime     Time
2012-03-05   23         0.5   0.5
2012-12-12   0          1.0   1.0

当然,最好将Time作为DateTime列的一部分。如果你愿意,你可以练习一下:)

这种方法相当快:在我的笔记本电脑上,对4700万行进行分组大约需要3分钟。在

从这个数据帧开始:

df = pd.DataFrame({'Employee': list('ABCDEFGH'), 
                   'Date': [1, 1, 1, 2, 2, 2, 3, 3],
                   'Time': [10, 10, 10, 11, 10, 11, 11, 12]})
print(df)

输出:

^{pr2}$

您可以按DateTime分组并计算员工数:

per_hour = df.groupby(['Date', 'Time']).count()
per_hour['EmpFactor'] = 1 / per_hour.Employee
print(per_hour)

输出:

           Employee  EmpFactor
Date Time                     
1    10           3   0.333333
2    10           1   1.000000
     11           2   0.500000
3    11           1   1.000000
     12           1   1.000000

相关问题 更多 >