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?
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.
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. .
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.
You can join
a string on the series directly:
In [3]:
' '.join(df['text'])
Out[3]:
'Hello world !'
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