Вы можете создать словарь, сопоставляющий дочерние элементы с родителями.
Затем используйте pd.Series.apply
для построения строки пути с помощью цикла while
.
Примечание. Предполагается, что null
фактически означаетNaN
, что более целесообразно для числового столбца.
child_parent_dict = df.set_index('EMPLOYEE_ID')['MANAGER_ID'].to_dict()
def get_all_parents(child):
"""Get all parents from hierarchy structure"""
while child == child:
child = child_parent_dict[child]
if child == child:
yield int(child)
def get_path(x):
"""Calculate path and construct string"""
return '/'.join(list(map(str, [x]+list(get_all_parents(x)))))
df['Path'] = df['EMPLOYEE_ID'].apply(get_path)
print(df)
# EMPLOYEE_ID NAME MANAGER_ID Path
# 0 101 A 10 101/10/1
# 1 102 B 11 102/11/1
# 2 10 C 1 10/1
# 3 11 D 1 11/1
# 4 1 E NaN 1