Home > Net >  Convert a series of lists into a single list
Convert a series of lists into a single list

Time:03-29

I need to take a series that looks like the following where the rows are labelled A-D and the column I am interested in is called vals and consists of a list of integer values of varying length (but will never be null):

A                                            [1, 140]
B                                            [345, 567]
C                                            [400, 45, 12]
D                                            [1]

And convert it into a series that is just a single list that might look like (I no longer care about the row label at this point):

0                                            [1, 140, 345, 567, 400, 45, 12, 1]

I am not sure how to do this, what I have tried so far is unsuccessful as it gives me a list of lists which is not what I want, but I will add this below as I might be somewhere in the right region.

single_list = s.groupby(lambda x: True).apply(list).agg({"vals": list})

CodePudding user response:

Use Series.explode, but slowier if large DataFrame:

L = list(df['vals'].explode())

Or flatten values should be faster in large df:

L = [y for x in df['vals'] for y in x])
  • Related