首页 > 解决方案 > Python pandas员工层次递归函数

问题描述

df

Employee Id    Manager ID
1                3
2                1
3                4
4                NULL
5                NULL
6                7
7                5  and so on

因此,4 和 5 emp id 是 CXO。层级预期产出:(经理对他手下的员工)

Mgr Employees
1  2
2  None
3  1,2
4  3,1,2
5  7,6
6  None
7  6

例如,4 是 3(1 级)的经理,3 是 1(2 级)的经理,1 是 2(3 级)的经理。

任何人都可以帮忙。我知道它使用 SQL,但只需要 pandas 的解决方案

标签: pythonpandasdataframe

解决方案


我们可以使用networkx创建一个DiGraph具有源 asManager ID和目标 as的连接Employee Id,然后nx.descendants在列表推导中使用我们可以获得从源可访问的所有节点:

import networkx as nx

G = nx.from_pandas_edgelist(
    df, 'Manager ID', 'Employee Id', create_using=nx.DiGraph())

s = [','.join(map(str, nx.descendants(G, i))) for i in df['Employee Id']]
d = pd.DataFrame({'Manager': df['Employee Id'].tolist(), 'Employee': s}).replace('', np.nan)

结果:

print(d)

   Manager Employee
0        1        2
1        2      NaN
2        3      1,2
3        4    1,2,3
4        5      6,7
5        6      NaN
6        7        6

推荐阅读