在Pandas数据框中合并具有相同名称的多个列 [英] Combining multiple columns with same name in pandas dataframe

查看:45
本文介绍了在Pandas数据框中合并具有相同名称的多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

pp  b          pp   b
5   0.001464    6   0.001853
5   0.001459    6   0.001843

是否可以组合具有相同名称的列?我只希望将此作为输出:

Is there a way to combine columns with the same name? I just want this as output:

pp  b         
5   0.001464    
5   0.001459    
6   0.001853
6   0.001843


推荐答案

尝试 groupby 且轴= 1

df.groupby(df.columns.values, axis=1).agg(lambda x: x.values.tolist()).sum().apply(pd.Series).T.sort_values('pp')
Out[320]: 
          b   pp
0  0.001464  5.0
2  0.001459  5.0
1  0.001853  6.0
3  0.001843  6.0

使用 wide_to_long

s=pd.Series(df.columns)
df.columns=df.columns+s.groupby(s).cumcount().astype(str)

pd.wide_to_long(df.reset_index(),stubnames=['pp','b'],i='index',j='drop',suffix='\d+')
Out[342]: 
            pp         b
index drop              
0     0      5  0.001464
1     0      5  0.001459
0     1      6  0.001853
1     1      6  0.001843

这篇关于在Pandas数据框中合并具有相同名称的多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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