Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate all strings in the dataframe column

Tags:

python

pandas

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"
like image 562
Sai Kumar Avatar asked Aug 16 '18 07:08

Sai Kumar


People also ask

How do you concatenate strings in a data frame?

By use + operator simply you can concatenate two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.

How do I concatenate all rows in a DataFrame?

Use DataFrame.append() method to concatenate DataFrames on rows. For E.x, df. append(df1) appends df1 to the df DataFrame.

How do you concatenate values in a column in Python?

To start, you may use this template to concatenate your column values (for strings only): df['New Column Name'] = df['1st Column Name'] + df['2nd Column Name'] + ... Notice that the plus symbol ('+') is used to perform the concatenation.

How do I concatenate certain columns in pandas?

Concatenating string columns in small datasets For relatively small datasets (up to 100–150 rows) you can use pandas.Series.str.cat() method that is used to concatenate strings in the Series using the specified separator (by default the separator is set to '' ).


1 Answers

Use join with whitespace:

out = ' '.join(df["read"])
print (out)
Red is my favorite color
like image 93
jezrael Avatar answered Sep 20 '22 18:09

jezrael