python - 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 name
andage
和聚合执行了一个组,以给出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
解决方案
使用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
推荐阅读
- express - 如何为 Exress JS 应用程序设置哨兵上下文?
- python - 使用moviepy将具有透明背景的Gizeh gif添加到现有电影
- html - WhatsApp 节点 js 中的 Bot 框架 V4 人工切换
- java - 如何偶然获得有效且正确的掉落系统
- javascript - 我安装的 vue-scroll-sync 包不起作用
- swift - 如何快速跟踪出现在 tableView 中的新单元格?
- react-native - 生产中的 React Native 信息 plist
- azure-devops-server-2019 - 反向代理背后的 AzureDevOps OnPremise
- python - Python PPTX:获取表格边框颜色
- php - 当我将 Joomla 网站上的表单数据保存到数据库时,Joomla 将我注销