首页 > 解决方案 > 如何在 Python 中连接 Pandas 系列的行

问题描述

我有一个包含许多行的 Python 熊猫系列,这些行包含一个单词列表,例如:

25     [estimated, million, people, lived, vulnerable...
176                                   [cent, vulnerable]
7      [create, sound, policy, frameworks, poor, vuln...
299    [create, sound, policy, frameworks, cent, vuln...
283    [missing, international, levels, based, estima...
                             ...                        
63     [create, sound, policy, frameworks, world, pop...
259             [build, world, population, still, lived]
193    [create, sound, policy, frameworks, every, sta...
284    [cent, situation, remains, particularly, alarm...
43     [based, less, cent, share, property, inheritan...
Name: clean_text, Length: 300, dtype: object

如何将所有行的单词连接到一个列表中?我试过了:

nameofmyfile.str.cat(sep=', ')

但我得到一个错误:

TypeError:不能将 .str.cat 与推断的 dtype 'mixed' 的值一起使用。

标签: pythonpandas

解决方案


这是一个hacky方式。

# step 1: Convert to a list
our_list = df["series"].tolist()

# step 2: Make a new empty list and build it up
new_list = []
for words in our_list:
    new_list += words

推荐阅读