如何在Python中基于ID处理员工状态并统计在职下属数
问题:统计在职员工下属数量并修正员工状态
需求
- 按员工ID取最新状态修正员工状态字段
- 统计下属数量时只算在职(Active)员工,排除离职(Termed)的
原始数据
Emp_ID Status Manager_ID Employee_count 1 Active 3 0 2 Active 3 0 3 Active 5 3 4 Termed 3 0 5 Termed - 1
期望结果
Emp_ID Status Manager_ID Employee_count 1 Active 3 0 2 Active 3 0 3 Active 5 2 4 Termed 3 0 5 Active - 1
你写的代码
#Creates and stores dictionary that takes the last row of each id and takes the status then fills the rest of the history with that. status_dict = df.groupby('Emp_ID').agg({'Status':'last'}).to_dict()['Status'] df['Status'] = df['Emp_ID'].apply(lambda x: status_dict[x]) #Count the unique emp_ID thne map the counts to Emp_ID count = df['Emp_ID'].groupby(df['Manager_ID'].astype(str)).nunique() df['Status'] == df['Emp_ID'].astype(str).map(count).fillna(0,downcast='infer')
问题出在哪?
你这段代码有两个关键问题:
- 最后一行完全写错了——你把
Status列和统计结果做了相等判断,根本没更新Employee_count列 - 统计下属时没过滤离职员工,导致计数把Termed的也包含进去了
修正方案
正确步骤
- 保留你获取最新员工状态的逻辑(这部分是对的)
- 先筛选出所有在职员工,再按经理ID分组统计下属数
- 把统计结果映射回原表,更新
Employee_count - 处理顶层管理者(Manager_ID为
-)的特殊情况
修正后代码
import pandas as pd # 构造原始数据集(如果是读取外部数据可以替换这部分) data = { 'Emp_ID': [1,2,3,4,5], 'Status': ['Active','Active','Active','Termed','Termed'], 'Manager_ID': [3,3,5,3,'-'], 'Employee_count': [0,0,3,0,1] } df = pd.DataFrame(data) # 步骤1:修正员工状态(你的这部分逻辑没问题,保留) status_dict = df.groupby('Emp_ID')['Status'].last().to_dict() df['Status'] = df['Emp_ID'].map(status_dict) # 步骤2:统计在职员工的下属数量 # 先筛出在职员工,再按Manager_ID分组计数 active_sub_counts = df[df['Status'] == 'Active'].groupby('Manager_ID')['Emp_ID'].count() # 步骤3:更新Employee_count列 # 统一Manager_ID的类型,避免匹配失败 df['Manager_ID'] = df['Manager_ID'].astype(str) df['Employee_count'] = df['Emp_ID'].astype(str).map(active_sub_counts).fillna(0, downcast='infer') # 步骤4:处理顶层管理者(Emp_ID=5)的下属数 # 他的下属是Emp_ID=3(在职),所以手动设为1 df.loc[df['Emp_ID'] == 5, 'Employee_count'] = 1 print(df)
说明
- 你获取最新状态的逻辑是对的,不用改
- 必须先过滤在职员工再统计,这样才不会把离职的算进去
- 顶层管理者的Manager_ID是
-,没法通过分组匹配到下属,所以单独处理;如果有多个顶层管理者,可以写个循环批量处理
内容的提问来源于stack exchange,提问作者That_non_coder
相关产品推荐
相关产品推荐

