python/pandas 递归迭代

问题描述 投票:0回答:1
emp_id 员工 等级 经理_id 经理
100 萨姆 1 100 萨姆
200 杰克 2 100 萨姆
300 吉尔 2 100 萨姆
400 克莱尔 3 200 杰克
500 芦苇 3 300 吉尔
600 井架 4 400 克莱尔
700 比尔 4 500 芦苇

我有一个表格,其中包含员工及其各自的经理,分别位于“emp”和“manager”列中。 “级别”列中的数字代表组织内“emp”列中员工的不同级别。

如何在 python(pandas) 中编写脚本以从上一级获取经理名称作为步骤等中的条目。

emp_id 员工 级别 经理_id 经理 l1 l2 l3 l4
100 萨姆 1 100 萨姆
200 杰克 2 100 萨姆 萨姆
300 吉尔 2 100 萨姆 萨姆
400 克莱尔 3 200 杰克 萨姆 杰克
500 芦苇 3 300 吉尔 萨姆 吉尔
600 井架 4 400 克莱尔 萨姆 杰克 克莱尔
700 比尔 4 500 芦苇 萨姆 吉尔 芦苇

这就是我试图根据每个员工的主管层次结构递归确定每个员工的领导级别

df = pd.DataFrame(data)

# Create a dictionary to store leadership levels
leadership_levels = {}

# Create a function to recursively determine leadership levels
def determine_leader(emp_id, level):
    # Find the supervisor for the current employee
    manager_id = df.loc[df['emp_id'] == emp_id, 'manager_id'].values[0]
    
    if manager_id is not None:
        # Recursively determine the supervisor's leadership level
        determine_leader(manager_id, level + 1)
        # Update the leadership_levels dictionary
        leadership_levels[level] = df.loc[df['emp_id'] ==manager_id, 'emp'].values[0]

# Determine leadership levels for each employee
for index, row in df.iterrows():
    determine_leader(row['emp_id'], 1)

# Add the leadership levels to the DataFrame
for level, leader in leadership_levels.items():
    df[f'level_{level}_leader'] = leader

# Display the resulting DataFrame
print(df)
python pandas dataframe iteration
1个回答
0
投票

这种类型的层次结构最好通过为您的员工及其经理(也可能有相应的经理)提供适当的数据结构来实现。

这不仅仅是一个 pandas 问题,如果您只关心直接管理者,这似乎是为了找到正确的算法来找到分层树的“根”或中间节点。

这是一个很好的起点:https://algs4.cs.princeton.edu/15uf/

© www.soinside.com 2019 - 2024. All rights reserved.