【问题标题】:Convert A Column and Column B In Pandas to One Long String (Python 3)将 Pandas 中的 A 列和 B 列转换为一个长字符串(Python 3)
【发布时间】:2019-07-09 13:23:35
【问题描述】:

enter image description here如何将 pandas 的列转换为一个长字符串?

例如,转换以下DF:

column1 column2 
John    Noun
Went    Verb
To      DT[enter image description here][2]
Fetch   Verb
His     AD
Ball    Noun

读作

关键字 John/Noun went/Verb to/DT fetch/Verb his/AD Ball/Noun

有什么帮助吗?

【问题讨论】:

    标签: python python-3.x string pandas


    【解决方案1】:

    用分隔符连接列并调用join:

    s = ' '.join(df['Keyword'] + '/' + df['Tag'])
    

    或者使用str.cat:

    s = ' '.join(df['Keyword'].str.cat(df['Tag'], sep='/'))
    

    如果需要连接所有列,请使用apply:

    s = ' '.join(df.apply( '/'.join, axis=1))
    #if possible some non strings columns
    #s = ' '.join(df.astype(str).apply( '/'.join, axis=1))
    

    print (s)
    John/Noun Went/Verb To/DT Fetch/Verb His/AD Ball/Noun To read/as
    

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2019-01-14
      • 2018-04-24
      相关资源
      最近更新 更多