按一列分组,并找出另一列中唯一值的数量

2024-05-15 08:34:45 发布

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

我有一个如下的数据帧

         date  hour staff
0  2019-10-01     6     A
1  2019-10-01     6     B
2  2019-10-01     6     C
3  2019-10-02     6     D
4  2019-10-02     6     B
5  2019-10-02     6     A
6  2019-10-03     6     B
7  2019-10-03     6     B
8  2019-10-03     6     B
9  2019-10-01     7     D
10 2019-10-01     7     A
11 2019-10-01     7     B
12 2019-10-01     7     C
13 2019-10-02     7     D
14 2019-10-02     7     C
15 2019-10-02     7     A
16 2019-10-03     7     B
17 2019-10-03     7     B
18 2019-10-03     7     A

我想计算每小时唯一员工的平均值,如下

工作人员小时数
6.2
7.3

说明:
第6小时,
独特的员工=2
10月1日:3(A,B,C)+10月2日:3(D,B,A)+10月3日:1(B)=3+3+1=7/3(唯一日期数)~2

第7小时,
独特的员工=3
10月1日:4(D,A,B,C)+10月2日:3(D,C,A)+10月3日:2(B,A)=4+3+2=9/3(唯一日期数)~3


Tags: 数据date员工平均值staff小时工作人员hour
2条回答
df.groupby(['hour', 'date'])['staff'].nunique().reset_index()\
  .groupby('hour')['staff'].mean().round()

>>> output

6   2.0
7   3.0

编辑:

ankyƏu 91在评论中的解决方案要快得多,应该明确使用:

df.groupby(['date','hour'])['staff'].nunique().mean(level=1).round()

我没有足够的声誉发表评论-在第一个解决方案中第二次包含['staff']是虚假的。把reset\u index()放在末尾也稍微好一点。你知道吗

df.groupby(['date','hour'])['staff'].nunique().groupby('hour').mean().round().reset_index()

使用agg的替代语法:

df.groupby(['date','hour']).agg(lambda x: x.nunique()).groupby('hour').mean().round() \
.reset_index()

如果您真的希望结果是int,可以用astype(int)替换mean()

df.groupby(['date','hour'])['staff'].nunique().mean(level=1).astype(int).reset_index()

相关问题 更多 >