19

I want to convert all the strings in a dataframe column as a single empty string and then convert it in to list of words:

import pandas as pd
df = pd.DataFrame({'read': ["Red", "is", "my", "favorite", "color"]})
print(df)
    read
0   Red
1   is
2   my
3   favorite
4   color

I tried to join strings but I don't know how to add space.

string = ""
for i,j in df.iterrows():
    string += j["read"]

Output:

'Redismyfavoritecolor' 

Required Output:

"Red is my favorite color"

2 Answers 2

42

Use join with whitespace:

out = ' '.join(df["read"])
print (out)
Red is my favorite color
Sign up to request clarification or add additional context in comments.

4 Comments

I am getting a type error when I try it in my dataframe. It's says expected str instance but got float. How can I fix it?
@sai_636 - How working ' '.join(df["read"].astype(str)) or ' '.join(df["read"].dropna()) if float values are NaNs
This code ' '.join(df["read"].astype(str)) this fixed it. Does this line convert all values to string before joining?
@sai_636 exactly, it convert values to string.
1

The easiest and optimal solution for concatenating or joining all strings in a column (Series) is to use pandas.Series.str.cat which lets you specify a separator.

df['read'].str.cat(sep=' ')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.