首页 > 解决方案 > Pandas - 按列分组,然后从结果创建新列

问题描述

我有一个 DataFrame,其中包含不同人的“测试结果”,每个人进行多次测试。它有列name, age,score

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

我已经通过 on nameandage和聚合执行了一个组,以给出max_score每个组的值(这是每年个人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

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

IE

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

标签: pythonpandas

解决方案


使用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

推荐阅读