data df
child parent b a c a d b e c f c g f
output:
child parent level
b a 1
c a 1
d b 2
e c 2
f c 2
g f 3
based on this parent child reporting, 'a' is the main parent as it is not reporting to anyone. 'b' and 'c' are reporting to 'a' so they are level = 1. 'd' and 'e' are reporting to level 1 (b,c) so they are level =2. 'g' is reporting to 'f'(which is level 2), so level = 3 for 'g'. please let me know how to achieve this
i was trying this below code but its not working
df['Level'] = np.where(df['parent'] == 'a',"level 1",np.nan)
dfm1 = pd.Series(np.where(df['Level'] == 'level 1', df['parent'],None))
df.loc[df['parent'].isin(dfm1),'Level'] = "level 2"