簡體   English   中英

Python Pandas將一系列字符串連接成一個字符串

[英]Python Pandas concatenate a Series of strings into one string

在python pandas中,有一個str值的Series / dataframe列要組合成一個長字符串:

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

目標:'Hello world!'

到目前為止,諸如df['text'].apply(lambda x: ' '.join(x))方法只返回Series。

達到目標連接字符串的最佳方法是什么?

您可以直接在系列中join字符串:

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

Out[3]:
'Hello world !'

除了join之外,您還可以使用pandas string方法.str.cat

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

但是, join()要快得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM