pandas 将不同行中的值连接起来 [英] Pandas Concatenate Values From Different Rows

查看:69
本文介绍了 pandas 将不同行中的值连接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此数据框:

import pandas as pd
a=pd.DataFrame({'number':[2,2,3],'A':['abc','def','ghi']})

a
    A   number
0   abc     2
1   def     2
2   ghi     3

我需要按索引顺序从具有相同数字值(以';分隔)的行中连接值; '.

I need to concatenate values, in order of index, from rows with the same number value, separated by '; '.

所需结果:

    A           number
0   abc; def    2; 2
2   ghi         3

到目前为止,我以为我可以隔离数据框,然后以某种方式尝试将它们连接在一起:

So far, I thought I could isolate the dataframes and then somehow try to join them together like this:

a['rank']=a.groupby('number').rank()
a1=a.loc[a['rank']==1]
a2=a.loc[a['rank']==2]
b=a1.merge(a2,on='number',how='left')
b=b.fillna('')

b
    A_x     number  rank_x  A_y     rank_y
0   abc     2   1.0     def     2
1   ghi     3   1.0     

..然后每列都只是这样的问题:

..and then it's just a matter of something like this per column:

b['A'] = b['A_x']+'; '+b['A_y']

...但是还有一种更简洁的方法(也许一次用于所有列)吗?

...but is there a more concise way to do this (perhaps for all columns at once)?

提前谢谢!

推荐答案

使用groupby + agg-

a.astype(str).groupby(a.number, as_index=False).agg('; '.join)

          A number
0  abc; def   2; 2
1       ghi      3

感谢MaxU的优化!

这篇关于 pandas 将不同行中的值连接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆