Python Pandas concatenates a series of lines into one line

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

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

Goal: "Hello world!"

Until now, methods such as df['text'].apply(lambda x: ' '.join(x))that have returned only the Series.

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

+4
source share
2 answers

You can joinline by line directly:

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

Out[3]:
'Hello world !'
+7
source

Besides join, you can also use the pandas string method.str.cat

In [171]: df.text.str.cat(sep=' ')
Out[171]: 'Hello world !'

However, it join()runs much faster.

+2
source

Source: https://habr.com/ru/post/1665356/


All Articles