Py学习  »  Python

python在经理和员工ID之间进行递归查找

Kumar AK • 5 年前 • 1681 次点击  

我有一个数据框如下

    import pandas as pd
    import numpy as np
    raw_data = {'Emp_ID':[144,220,155,200],
            'Mgr_ID': [200, 144,200,500], 
       'Type': ['O','I','I','I'],
        'Location' : ['India','UK','UK','US']
    }

    df2 = pd.DataFrame(raw_data, columns = ['Emp_ID','Mgr_ID', 'Type','Location'])

    print(df2)

enter image description here

希望输出如下

enter image description here

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53396
 
1681 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Andy L.
Reply   •   1 楼
Andy L.    5 年前

查找父/子或id之间的关系与图论有关,因此最好使用 Networkx package . 你需要把它安装到 pip g 使用networkx from_pandas_edgelist Emp_ID . 呼叫 nx.ancestors 对于每个使用genex(或者listcomp,如果您愿意)并将其传递给创建dataframe的员工 df3 . 最后, explode Mgr_ID 然后加入到 df2

import pandas as pd
import networkx as nx

g = nx.from_pandas_edgelist(df2, source='Mgr_ID', target='Emp_ID', create_using=nx.DiGraph)

df3 = pd.DataFrame(([list(nx.ancestors(g, x)), x] for x in df2.Emp_ID), 
                   index=df2.index, columns=['Mgr_ID', 'Emp_ID'])

df_final = df3.explode('Mgr_ID').join(df2[['Type', 'Location']])

Out[23]:
  Mgr_ID  Emp_ID Type Location
0    200     144    O    India
0    500     144    O    India
1    144     220    I       UK
1    500     220    I       UK
1    200     220    I       UK
2    200     155    I       UK
2    500     155    I       UK
3    500     200    I       US