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

Python Pandas concatenate a Series of strings into one string

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

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

目标:'Hello world !'

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

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

您可以直接join系列上的字符串:

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

Out[3]:
'Hello world !'

除了join,您还可以使用pandas字符串方法.str.cat

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

但是,join()要快得多。

您的代码是“returning the series”,因为您没有指定正确的轴。试试这个:

df.apply(' '.join, axis=0)
text    Hello world !
dtype: object

指定轴=0 将每列 中的所有值组合起来,并将它们放在一个字符串中。 return类型是一个系列,索引标签是列名,值是对应的连接字符串。如果您想一次将多个列合并为一个字符串,这将特别有用。

通常我发现在使用应用时很难理解您需要哪个轴,所以如果它没有按照您认为的方式工作,请始终尝试沿着另一个轴应用。