【发布时间】:2017-01-10 12:24:13
【问题描述】:
这个问题与之前的this posted 相同。我想连接三列而不是连接两列:
这里是两列的组合:
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
我想用这个命令合并三列,但它不起作用,你知道吗?
df['combined']=df.apply(lambda x:'%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)
【问题讨论】:
-
如果你想连接 3 列你需要 3 %s。 (%s_%s_%s) 喜欢
df['combined']=df.apply(lambda x:'%s_%s_%s' % (x['bar'],x['foo'],x['new']),axis=1) -
一个更全面的答案显示多种方法的时间是Combine two columns of text in pandas dataframe