# 如何根据层次结构计算列值

##### 问题描述投票：6回答：3

``````           Name         Stage  Highest_Stage_Reached
1         Barry         Child
5           Ben         Baby
``````

``````           Name         Stage  Highest_Stage_Reached
``````
python pandas numpy
##### 3个回答
1

``````df['Stage'] = pd.Categorical(df['Stage'], ordered=True, categories=['Baby', 'Child','Teenager','Adult'])

df['Highest_Stage_Reached'] = df.groupby('Name').Stage.transform('max')

Name    Stage       Highest_Stage_Reached
``````

3

``````d={'Baby':0,'Child':1,'Teenager':2,'Adult':3}
df['rank']=df.Stage.map(d)
df['Highest_Stage_Reached']=df.groupby('Name')['rank'].transform('max').\
map({v: k for k, v in d.items()})
print(df.drop('rank',1))

Name     Stage Highest_Stage_Reached
``````

1

``````l = ['Baby', 'Child', 'Teenager', 'Adult']

cond = [df['Stage'] == 'Baby',df['Stage'] == 'Child',df['Stage'] == 'Teenager',df['Stage'] == 'Adult']
df['Highest_Stage_Reached'] = np.select(cond, [0,1,2,3])

Name     Stage  Highest_Stage_Reached
1  Barry     Child                      1
5    Ben      Baby                      0

df['Highest_Stage_Reached'] = (df.groupby('Name')['Highest_Stage_Reached'].transform(max))

Name     Stage  Highest_Stage_Reached
1  Barry     Child                      3
5    Ben      Baby                      3

df['Highest_Stage_Reached'] = df['Highest_Stage_Reached'].apply(lambda x: l[x])
print(df)
``````

``````    Name     Stage Highest_Stage_Reached