【问题标题】:Convert A Column In Pandas to One Long String (Python 3)将 Pandas 中的一列转换为一个长字符串(Python 3)
【发布时间】:2015-10-30 05:22:38
【问题描述】:

如何将 pandas 列转换为一个长字符串?

例如,转换以下DF:

Keyword
James
Went
To
The
Market

读作

Keyword
James went to the market

有什么帮助吗?

【问题讨论】:

    标签: python string python-3.x pandas dataframe


    【解决方案1】:

    您可以先使用.tolist 将列转换为列表,然后使用.join 方法将所有单独的单词连接在一起。

    print(df)
    
      Keyword
    0   James
    1    Went
    2      To
    3     The
    4  Market
    
    ' '.join(df['Keyword'].tolist())
    
    # output: 'James Went To The Market'
    
    # or to put them in a dataframe with 1 row 1 column
    pd.DataFrame(' '.join(df['Keyword'].tolist()), columns=['Keyword'], index=[0])
    
                        Keyword
    0  James Went To The Market
    

    【讨论】:

      【解决方案2】:

      您可以使用str.cat 将字符串连接到带有您选择的分隔符的列中:

      >>> df.Keyword.str.cat(sep=' ')
      'James Went To The Market'
      

      然后您可以将此字符串放回 DataFrame 或 Series。

      注意:如果你不需要任何分隔符,你可以简单地使用df.sum()(之后你不需要构造一个新的DataFrame)。

      【讨论】:

        猜你喜欢
        • 2019-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-07
        • 1970-01-01
        • 2022-10-23
        • 2018-06-15
        • 2020-11-30
        相关资源
        最近更新 更多