2017-08-29 64 views
1

我有一個兩列csv:員工編號'eid'和經理的員工編號'mid'。試圖獲得python代碼,這將會爲每個員工添加顯示經理的職員id到CEO的列。 CEO的員工ID爲1.最終,我想將結果寫回csv。來自經理和員工ID的python層次結構

所以數據的模樣:

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的陳述,然後發現該經理的經理等等,直到我到達首席執行官。我一直在沿着這些線路嘗試:

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

回答

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') 
+0

這兩種方法都可行 - 謝謝!我需要研究他們爲什麼要工作,但這對我取得進步確實有幫助 - 無論是在我的任務還是在我的學習中。 – QuillPy