如何在Python中连接Pandas系列的行

2024-04-28 23:57:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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: Cannot use .str.cat with values of inferred dtype 'mixed'.


Tags: 列表worldcreatepolicy单词centcatbased
2条回答

这是一条很难的路

# 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

@Alexis给出的解决方案很好,但我始终反对使用循环并投票支持向量化。我创建了非常类似的系列,就像上面提到的一样,即:

>>> a
foo    [hi, hello, hey]
bar     [I, me, myself]
dtype: object

现在,使用numpy中的concatenate方法,将foo, bar的列表连接在一起,以形成单个元素数组:

>>> import numpy as np
>>> np.concatenate(a.values)
array(['hi', 'hello', 'hey', 'I', 'me', 'myself'], dtype='<U6')

现在我认为返回的numpy数组不应该有任何问题,但是如果您希望以列表的形式输出,可以使用内置的list()方法或numpy.ndarray的.tolist()方法以列表的形式获得输出

相关问题 更多 >