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?
Convert All Columns to Strings If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df. astype(str) methods.
get_value() function is used to quickly retrieve the single value in the data frame at the passed column and index. The input to the function is the row label and the column label.
Use the T attribute or the transpose() method to swap (= transpose) the rows and columns of pandas. DataFrame . Neither method changes the original object but returns a new object with the rows and columns swapped (= transposed object).
Render a DataFrame to a console-friendly tabular output. Buffer to write to. If None, the output is returned as a string.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With