gpt4 book ai didi

python - Pandas - 将多个组行合并为一行

转载 作者:行者123 更新时间:2023-12-02 15:48:50 25 4
gpt4 key购买 nike

一段时间以来,我一直在用头撞墙,试图在 Pandas 中找出这个看似简单的数据操作任务,但是我没有成功弄清楚如何去做或谷歌搜索足够的答案:(

我想要做的就是将下面片段左侧的表格(将是一个 pandas 数据框)并将其转换为右侧的表格(成为另一个 pandas 数据框)。

enter image description here

创建初始数据框的代码:

import pandas as pd

test_data = pd.DataFrame(
{
'team': [1,1,2,2,3,3,4,4,5,5] ,
'player': ['a','b','c','d','e','f','g','h','i','j'] ,
'score': [10,22,66,44,1,3,55,6,4,2]
}
)

提前感谢您的帮助!

最佳答案

试试这个,

test_data.groupby('team').agg({'player':['first', 'last'], 'score': ['first', 'last']})

O/P:

    player_first player_last  score_first  score_last
team
1 a b 10 22
2 c d 66 44
3 e f 1 3
4 g h 55 6
5 i j 4 2

完整的解决方案:

test_data = test_data.groupby('team').agg({'player':['first', 'last'], 'score': ['first', 'last']})
test_data.columns = ['_'.join(x) for x in test_data.columns]
test_data = test_data.reset_index()
test_data = test_data[['team', 'player_first', 'score_first', 'player_last', 'score_last']]

O/P:

   team player_first  score_first player_last  score_last
0 1 a 10 b 22
1 2 c 66 d 44
2 3 e 1 f 3
3 4 g 55 h 6
4 5 i 4 j 2​
  • 你需要的是 groupby 和 first 和 last 的聚合操作
  • 设置列名
  • 重置索引并重新排序列

关于python - Pandas - 将多个组行合并为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73251746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com