Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert A Column In Pandas to One Long String (Python 3)

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?

like image 586
user3682157 Avatar asked Aug 06 '15 21:08

user3682157


People also ask

How do I convert a column to a string in Python?

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.

How can I get single value as a string from pandas data frame?

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.

How do I turn a column into a row in pandas?

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

What does To_string do in pandas?

Render a DataFrame to a console-friendly tabular output. Buffer to write to. If None, the output is returned as a string.


2 Answers

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
like image 169
Jianxun Li Avatar answered Oct 21 '22 13:10

Jianxun Li


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

like image 27
Alex Riley Avatar answered Oct 21 '22 14:10

Alex Riley