python - 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 的解决方案
解决方案
我们可以使用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
推荐阅读
- opentok - OpenTok 说支持 Safari 13 ScreenSharing
- mule - 如何访问域项目(Mule)中定义的属性占位符?
- abap - 在屏幕上验证 SELECT-OPTIONS 值?
- java - 使用具有相同 XML 类型名称的两个类
- r - R - 合并两个表并计算变量之间的转移
- excel - 在 Excel 上的 Oracle Fusion Cloud 中安装 ADF 插件时出错
- css - 如何强制电子根据新的 css 更新渲染?
- java - OpenCsv - 在字段上设置自定义验证
- sql - 在数据库中存储 .sql 类型文件的正确方法是什么?
- javascript - FormData 追加列表对象