简体   繁体   中英

How to concatenate rows of a Pandas series in Python

I have a Python pandas series containing many rows, and these rows contain a list of words, eg:

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

How can I concatenate all of the rows' words into a single list? I've tried:

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

But I got an error:

TypeError: Cannot use.str.cat with values of inferred dtype 'mixed'.

Here is a hacky way.

# 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

The given solution is good by @Alexis, but I'm always against using loops and vote for vectorization. I have created very similar Series just like given in question, which is:

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

Now using concatenate method from numpy, the lists of foo, bar will be concatenated together to form a single array of elements:

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

Now I dont think there should be any problem with a numpy array returned, still if you want output as list you can use inbuilt list() method or numpy.ndarray's .tolist() method to get output as a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM