简体   繁体   中英

How to create a single list from rows of lists?

I have a dataframe where one of my columns includes rows of lists.

Each individual row in my column is a list of elements.

I want to create ONE list that includes all the values from each row.

I have tried

final_list = list(itertools.chain.from_iterable(mylist)) 

but this keeps each row has a list.

The total length of all of my rows is 1981 . When I check for final_list it still has a length of 1981 which is wrong because each row has multiple elements in the lists.

I expect for the length of my final_list to have each row's list elements.

Assuming you are using pandas.DataFrame (marked as df in code), you can work it out using pandas.DataFrame.values.tolist() :

final_list = [item for sublist in df.values.tolist() for item in sublist]

Methodology of this list operation is described here .

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