合并组中的行 [英] Merge rows within a group together
本文介绍了合并组中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Pandas DataFrame,其中一些行对具有相同的ID但名称不同.我想要的是将行对减少到一行,并显示它们的两个名称.
I have a pandas DataFrame where some pairs of rows have the same ID but different name. What I want is to reduce the row pair to one row, and display both of their names.
输入:
ID NAME AGE
149 Bob 32
150 Tom 53
150 Roberts 53
151 Pamela 28
152 Andrew 23
输出:
ID NAME AGE
149 Bob 32
150 Tom Roberts 53
151 Pamela 58
152 Andrew 23
否则,我也可以执行['Tom','Roberts']或其他任何仍能捕获数据的方法.
Otherwise, I can also do ['Tom', 'Roberts'], or any other method that still captures the data.
推荐答案
使用 groupby
轻松完成.
df.groupby('ID', as_index=False).agg({'NAME' : ' '.join, 'AGE' : 'first'})
ID NAME AGE
149 Bob 32
150 Tom Roberts 53
151 Pamela 28
152 Andrew 23
这篇关于合并组中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文