【问题标题】:How to do column string concatenation including space separator in Pandas dataframe?如何在 Pandas 数据框中进行包含空格分隔符的列字符串连接?
【发布时间】:2019-05-25 07:08:09
【问题描述】:

我是一个Pandas DataFrame如下:

df = pd.DataFrame({
    'id': [1,2 ,3],
    'txt1': ['Hello there1', 'Hello there2', 'Hello there3'],
    'txt2': ['Hello there4', 'Hello there5', 'Hello there6'],
    'txt3': ['Hello there7', 'Hello there8', 'Hello there9']
})
df

id  txt1            txt2            txt3
1   Hello   there1  Hello there4    Hello there7
2   Hello   there2  Hello there5    Hello there8
3   Hello   there3  Hello there6    Hello there9

我想连接列txt1txt2txt3。到目前为止,我能够实现如下:

df['alltext'] = df['txt1']  + df['txt2'] + df['txt3']
df

id  txt1            txt2            txt3            alltext
1   Hello there1    Hello there4    Hello there7    Hello there1Hello there4Hello there7
2   Hello there2    Hello there5    Hello there8    Hello there2Hello there5Hello there8
3   Hello there3    Hello there6    Hello there9    Hello there3Hello there6Hello there9

但是如何在 Pandas 中连接时在两列字符串之间引入 空格 字符?

我刚刚开始学习 Pandas。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您还可以在列之间添加分隔符:

    df['alltext'] = df['txt1']  + ' ' + df['txt2'] + ' ' + df['txt3']
    

    或仅按DataFrame.filter 过滤列名中带有txt 的列,并在每行使用joinapply

    df['alltext'] = df.filter(like='txt').apply(' '.join, 1)
    

    或仅按 DataFrame.select_dtypes 过滤对象列 - 大多数情况下,具有对象 dtype 的 Series 将是 string - 但它可以是任何 Python object

    df['alltext'] = df.select_dtypes('object').apply(' '.join, 1)
    

    或按位置选择列 - 所有列都没有第一个 DataFrame.iloc

    df['alltext'] = df.iloc[:, 1:].apply(' '.join, 1)
    

    感谢@Jon Clements 提供的解决方案,以便更好地将列名与txt 和数字匹配:

    df['alltext'] = df.filter(regex=r'^txt\d+$').apply(' '.join, 1)
    

    【讨论】:

    • 人们可能想要考虑 .filter(regex=r'^txt\d+$') 只是为了明确明确需要哪些列,而不是 like='txt' 捡起不想要的东西的机会......(虽然 - 它会这是相当不可能的情况)
    • 有点吹毛求疵... 显然对象是字符串 - 不完全正确...它们不是 numpy 类型的对象...它们可能是 (虽然在大多数情况下不太可能)是 anything 而不是字符串 - 因此将str.join 应用于'em 会中断。 (请注意 - 如果您将愚蠢的东西存储在 DF/数组中,那么这本身就是一个完全不同的问题:p)
    • @JonClements - 是的,我想写得最好,也许这里的对象是字符串更好?还是熊猫对象中的大部分时间都是字符串?
    • 是的...也不知道如何措辞...我认为类似于“大多数时候具有对象 dtype 的系列将是一个字符串 - 但它可能是任何 Python 对象”...
    【解决方案2】:

    只需在其间添加空格

    df['alltext'] = df['txt1']  + ' ' + df['txt2'] + ' ' + df['txt3']
    

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      相关资源
      最近更新 更多