Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas concatenate a Series of strings into one string

In python pandas, there is a Series/dataframe column of str values to combine into one long string:

df = pd.DataFrame({'text' : pd.Series(['Hello', 'world', '!'], index=['a', 'b', 'c'])})

Goal: 'Hello world !'

Thus far methods such as df['text'].apply(lambda x: ' '.join(x)) are only returning the Series.

What is the best way to get to the goal concatenated string?

like image 743
cycle_about Avatar asked Dec 30 '16 17:12

cycle_about


People also ask

How do I combine a list of strings into one?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I join strings in pandas?

Python | Pandas Series.str.cat() to concatenate string Pandas str.cat() is used to concatenate strings to the passed caller series of string. Distinct values from a different series can be passed but the length of both the series has to be same. .

How do you concatenate 3 strings in Python?

Concatenation means joining strings together end-to-end to create a new string. To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.


1 Answers

You can join a string on the series directly:

In [3]:
' '.join(df['text'])

Out[3]:
'Hello world !'
like image 66
EdChum Avatar answered Sep 21 '22 06:09

EdChum