gpt4 book ai didi

python - 在 pandas python 中获取计数

转载 作者:太空宇宙 更新时间:2023-11-03 15:34:42 24 4
gpt4 key购买 nike

我有一个如下所示的数据框:

boss_id    employee_id      designation        
-1 100 CEO
100 39 Manager
100 4567 Manager
100 9843 Manager
39 47 entry level
39 45 entry level
4567 8 entry level
9843 9 entry level

在此boss_id给出了该员工的老板。指定是针对员工的。我想知道每个人总共管理多少人。

例如,由于首席执行官是终极人物,因此他应该管理此数据框中的所有 7 个人。经理只管理入门级。例如,员工 39 是一名经理,在此数据框中管理着 2 个人。最后,入门级别不管理任何人,​​因此其计数应该为 0。

我想要一个像这样的数据框:

boss_id    employee_id      designation              count
-1 100 CEO 7
100 39 Manager 2
100 4567 Manager 1
100 9843 Manager 1
39 47 entry level 0
39 45 entry level 0
4567 8 entry level 0
9843 9 entry level 0

我无法解决这个问题,任何帮助将不胜感激!提前致谢。

最佳答案

您可以递归调用employee_ids并找到他们的计数

    def findCount(employee_id):
if df.loc[df['employee_id'] == employee_id]['designation'].as_matrix()[0] == 'd':
return 0
eIds = df.loc[df['boss_id']==employee_id]['employee_id'].as_matrix()
cnt = 0
for eid in eIds:
cnt += (findCount(eid) + 1)
return cnt

for index, row in df.iterrows():
cnt = findCount(row['employee_id'])
df.loc[index, 'count'] = cnt

关于python - 在 pandas python 中获取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42618675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com