熊猫-按列分组,然后从结果中创建新列

时间:2020-09-01 10:04:06

标签: python pandas

我有一个DataFrame,其中包含针对每个人的多个人的“测试结果”。 它具有列nameagescore

scores = pd.DataFrame({'name': ['Alex', 'Alex', 'Alex', 'Alex', 'Alex', 'James', 'James', 'James', 'James', 'James', 'James', 'Emily', 'Emily', 'Emily', 'Emily', 'Emily', 'Emily', 'Emily'], 'age': [25, 26, 26, 27, 27, 25, 26, 26, 26, 27, 27, 25, 25, 26, 26, 26, 27, 27], 'score': [10, 0, 2, 1, 2, 2, 4, 6, 6, 10, 8, 4, 7, 6, 10, 9, 7, 10]})

     name  age  score
0    Alex   25     10
1    Alex   26      0
2    Alex   26      2
3    Alex   27      1
4    Alex   27      2
5   James   25      2
6   James   26      4
7   James   26      6
8   James   26      6
9   James   27     10
10  James   27      8
11  Emily   25      4
12  Emily   25      7
13  Emily   26      6
14  Emily   26     10
15  Emily   26      9
16  Emily   27      7
17  Emily   27     10

我对nameage进行了分组,并汇总得出每个组的max_score(这是{{1}的max值}每年针对某个人的列)

score

结果看起来像

age_scores = scores.groupby(['name','age']).agg({"score":'max'})

我希望有一个数据框,该数据框每人一行,然后是每个年龄段的最高分的一列

           score
name  age       
Alex  25      10
      26       2
      27       2
Emily 25       7
      26      10
      27      10
James 25       2
      26       6
      27      10

1 个答案:

答案 0 :(得分:2)

如果要转换pivot,请使用age_scores

(age_scores
     .reset_index()
     .pivot('name', 'age', 'score')
     .add_prefix('max_')
     .reset_index()
     .rename_axis(None, axis=1))

输出:

    name  max_25  max_26  max_27
0   Alex      10       2       2
1  Emily       7      10      10
2  James       2       6      10

否则,如果不需要age_scores作为中间数据帧,则克里斯在评论中提出的unstack解决方案可能更容易:

(scores
 .groupby(['name', 'age'])['score'].max()
 .unstack('age')
 .add_prefix('max_')
 .reset_index())

输出:

age   name  max_25  max_26  max_27
0     Alex      10       2       2
1    Emily       7      10      10
2    James       2       6      10
相关问题