Python Pandas 将一系列字符串连接成一个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41400381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:41:39  来源:igfitidea点击:

Python Pandas concatenate a Series of strings into one string

stringpython-3.xpandasstring-concatenationseries

提问by cycle_about

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

在 python pandas 中,有一个 str 值的 Series/dataframe 列组合成一个长字符串:

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.

到目前为止,诸如此类的方法df['text'].apply(lambda x: ' '.join(x))仅返回系列。

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

到达目标连接字符串的最佳方法是什么?

回答by EdChum

You can joina string on the series directly:

您可以join直接在系列上添加字符串:

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

Out[3]:
'Hello world !'

回答by Zero

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

除此之外join,您还可以使用Pandas字符串方法.str.cat

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

However, join()is much faster.

但是,join()速度要快得多。