【问题标题】:python hierarchy from manager and employee id来自经理和员工 ID 的 python 层次结构
【发布时间】:2017-09-01 00:02:35
【问题描述】:

我有一个包含两列的 csv:员工 ID 'eid' 和经理的员工 ID 'mid'。尝试获取 python 代码,该代码将为每个员工添加显示经理的员工 ID 的列,一直到 CEO。 CEO 的员工 ID 为 1。最终我想将结果写回 csv。

所以数据看起来像:

eid,    mid
111,    112
113,    112
112,    114
114,    115
115,    1

我期待这样的输出。请注意,虽然没有员工会有超过 4 级的经理,但我也想学习动态命名列的 python。

eid,    mid,    l2mid   l3mid   l4mid
111,    112,    114,    115,    1
113,    112,    114,    115,    1
112,    114,    115,    1   
114,    115,    1       
115,    1           

我对编码非常陌生,并试图自学但一直卡住。我的问题: 1) 我试图使用 for 语句在给定的行中使用mid,然后找到该经理的经理,依此类推,直到我到达 CEO。我一直在尝试这些方面:

df = pd.read_csv('employee.csv') 
if mid =! 1 
for i in df:
    df.['l2mid'] = df.loc[df.eid == [i], [mid]]

也许我正在倒退,我应该尝试按经理对所有员工进行分组?这段代码会有什么不同?

我在C#sql 中看到了解决方案,我也看到了构建treesjson 的解决方案。我非常感谢任何帮助和鼓励。

更新:下一步是添加国家/地区列 - 请参阅:entry here

【问题讨论】:

    标签: python hierarchy


    【解决方案1】:

    我相信有一个更好的解决方案,但这是可行的。我用零填空。

    a = []
    for index, row in df.iterrows():
        res = df[df['eid']==row['mid']]['mid'].values
        a.append(0 if not res else res[0])
    df['l2mid'] = a
    
    a = []
    for index, row in df.iterrows():
        res = df[df['eid']==row['l2mid']]['mid'].values
        a.append(0 if not res else res[0])
    df['l3mid'] = a
    
    a = []
    for index, row in df.iterrows():
        res = df[df['eid']==row['l3mid']]['mid'].values
        a.append(0 if not res else res[0])
    df['l4mid'] = a
    
    df
    # output :
    # eid   mid l2mid   l3mid   l4mid
    # 0 111 112 114 115 1
    # 1 113 112 114 115 1
    # 2 112 114 115 1   0
    # 3 114 115 1   0   0
    # 4 115 1   0   0   0
    

    您可以为例程定义一个函数。

    def search_manager(target_column, new_column):
        a = []
        for index, row in df.iterrows():
            res = df[df['eid']==row[target_column]]['mid'].values
            a.append(0 if not res else res[0])
        df[new_column] = a
    
    search_manager('mid', 'l2mid')
    search_manager('l2mid', 'l3mid')
    search_manager('l3mid', 'l4mid')
    

    【讨论】:

    • 这两种方法都有效 - 谢谢!我需要确切地研究它们为什么起作用,但这对我取得进步非常有帮助——无论是在我的任务中还是在我的学习中。
    • 你能否逐行解释这个答案。非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 2022-12-12
    • 2013-12-06
    相关资源
    最近更新 更多