使用panda在员工/经理层次结构中查找值



我有一种情况,我想查找当前附加到经理各自直接下属的值。经理级别的数据集如下所示:

MGR_ID        MGR_Value
1             Complete
2             InComplete

员工/经理层次结构如下:

EE_ID       MGR_ID
3           1
4           1
5           1
6           2
7           2

现在,下面的数据集具有经理/员工层次结构,我想在那里创建一个新列,在那里我可以为员工存储与经理相同的值。所以输出数据应该是这样的:

EE_ID       MGR_ID      MGR_Value      EE_Value
3           1           Complete       Complete
4           1           Complete       Complete
5           1           Complete       Complete
6           2           InComplete     InComplete
7           2           InComplete     InComplete

我应该如何在熊猫身上做到这一点?

先尝试合并,然后复制列:

import pandas as pd
df_manage = pd.DataFrame({
'MGR_ID': {0: 1, 1: 2},
'MGR_Value': {0: 'Complete', 1: 'InComplete'}
})
df_hierarchy = pd.DataFrame({
'EE_ID': {0: 3, 1: 4, 2: 5, 3: 6, 4: 7},
'MGR_ID': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2}
})
# Merge DataFrames Together
new_df = df_hierarchy.merge(df_manage, on='MGR_ID')
# Duplicate Column
new_df["EE_Value"] = new_df['MGR_Value']
# For Display
print(new_df.to_string())
EE_ID  MGR_ID   MGR_Value    EE_Value
0      3       1    Complete    Complete
1      4       1    Complete    Complete
2      5       1    Complete    Complete
3      6       2  InComplete  InComplete
4      7       2  InComplete  InComplete

最新更新