Python Pandas concatenate a Series of strings into one string

↘锁芯ラ 提交于 2019-11-27 07:44:01

问题


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?


回答1:


You can join a string on the series directly:

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

Out[3]:
'Hello world !'



回答2:


Apart from join, you could also use pandas string method .str.cat

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

However, join() is much faster.



来源:https://stackoverflow.com/questions/41400381/python-pandas-concatenate-a-series-of-strings-into-one-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!