连接字符串列,其中列名在列表中

时间:2018-07-05 14:31:12

标签: python pandas

我知道如何串联两列字符串。

df['a'] + ' ' + df['b']

但是如果列名列表很长,我就不能全部写出来。

这显然是不正确的,但我一直在思考...

' '.join([df[col] for col in columns])

4 个答案:

答案 0 :(得分:1)

您可以自己编写一个简单的求和函数(内置的sum仅适用于数字):

def concat(df, cols):
    out = df[cols[0]]
    for i in range(1, len(cols)):
        out = out + df[cols[i]]  # Note: `+=` would change the first column.
    return out

答案 1 :(得分:0)

我没有大熊猫的经验,但是您不能这样做:

' '.join(df[i] for i in columns.keys())

答案 2 :(得分:0)

您可以只使用DataFrame.sum指定正确的轴,它将把字符串连接在一起。

样本数据

import pandas as pd
df = pd.DataFrame({'a': ['hello', 'goodbye'], '34234': ['goodbye', 'seven'], 
                   'column2': ['foo-', 'bird'], 'column xx': ['bar', 'cat']})
#         a    34234 column2 column xx
#0    hello  goodbye    foo-       bar
#1  goodbye    seven    bird       cat

columns = ['a', 'column2', 'column xx']
(df[columns] + ' ').sum(axis=1).str.strip()  # strip removes the trailing space

输出:

0      hello foo- bar
1    goodbye bird cat

答案 3 :(得分:0)

df.columns将给出所有列。进行串联。

 ' '.join(df.columns)
相关问题