21

How can I convert a pandas column into one long string?

For example, convert the following DF:

Keyword
James
Went
To
The
Market

To read as

Keyword
James went to the market

Any help?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
user3682157
  • 1,625
  • 8
  • 29
  • 55

2 Answers2

23

You can first use .tolist to convert column to a list and then use .join method to concat all separate words together.

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
Jianxun Li
  • 24,004
  • 10
  • 58
  • 76
12

You could use str.cat to join the strings in a column with a separator of your choice:

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

You can then put this string back into a DataFrame or Series.

Note: if you don't need any separator, you can simply use df.sum() (and you don't need to construct a new DataFrame afterwards).

Alex Riley
  • 169,130
  • 45
  • 262
  • 238