【问题标题】:Pandas - Group by column and then create new columns from resultPandas - 按列分组,然后从结果创建新列
【发布时间】:2020-12-20 10:38:07
【问题描述】:

我有一个 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(这是每年个人score 列的max 值)

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

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

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

【问题讨论】:

标签: python pandas


【解决方案1】:

使用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 作为中间数据帧,那么 Chris 在 cmets 中提出的 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

【讨论】:

  • 谢谢!这非常有帮助,并且完全符合我的需要:)
  • 奇怪的是,虽然 reset_index 使 age 成为索引,但我似乎无法摆脱它
  • 是的,所以age 是列的名称。您可以使用df.columns.name = None 重置它,或者如果您想链接它,可以使用rename_axis 重置它。我已经更新了解决方案(其中的pivot 部分)以将该名称重置为无。如果你想了解更多细节,这里是thread on StackOverflow
猜你喜欢
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2020-11-11
  • 1970-01-01
相关资源
最近更新 更多