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?
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?
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
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).