如何将多个列值连接到Panda数据框中的单个列 [英] How to concatenate multiple column values into a single column in Panda dataframe

查看:48
本文介绍了如何将多个列值连接到Panda数据框中的单个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与先前发布的相同.我想串联三列而不是串联两列:

This question is same to this posted earlier. I want to concatenate three columns instead of concatenating two columns:

这是合并两列的内容:

df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})

df['combined']=df.apply(lambda x:'%s_%s' % (x['foo'],x['bar']),axis=1)

df
    bar foo new combined
0   1   a   apple   a_1
1   2   b   banana  b_2
2   3   c   pear    c_3

我想用此命令合并三列,但是不起作用,知道吗?

I want to combine three columns with this command but it is not working, any idea?

df['combined']=df.apply(lambda x:'%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)

推荐答案

使用DataFrame.apply()的另一种解决方案,当您想连接更多列时,键入的内容略少,可伸缩性更高:

Another solution using DataFrame.apply(), with slightly less typing and more scalable when you want to join more columns:

cols = ['foo', 'bar', 'new']
df['combined'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)

这篇关于如何将多个列值连接到Panda数据框中的单个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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