简体   繁体   English

如何从列表行创建单个列表?

[英]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 . 我所有行的总长度为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. 当我检查final_list时,它的长度仍然是1981 ,这是错误的,因为每一行在列表中都有多个元素。

I expect for the length of my final_list to have each row's list elements. 我期望final_list的长度包含每一行的list元素。

Assuming you are using pandas.DataFrame (marked as df in code), you can work it out using pandas.DataFrame.values.tolist() : 假设您使用的是pandas.DataFrame (在代码中标记为df),则可以使用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 . 这个列表的操作方法是描述在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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