将 Pandas 数据框转换为包含索引、数据和列的列表列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33679729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:13:27  来源:igfitidea点击:

Convert Pandas dataframe to list of list with index, data, and columns

pythonpython-2.7pandasdataframe

提问by user2242044

I have a Pandasdataframe that I'd like to convert to a list of list where each sublist is a row in the dataframe. How would I also include the index values so that I can later output it to PDF table with ReportLab

我有一个Pandas数据框,我想将其转换为列表列表,其中每个子列表都是数据框中的一行。我将如何还包括索引值,以便我稍后可以将其输出到 PDF 表中ReportLab

import pandas as pd
df = pd.DataFrame(index=['Index 1', 'Index 2'],
                  data=[[1,2],[3,4]],
                  columns=['Column 1', 'Column 2'])

list = [df.columns[:,].values.astype(str).tolist()] + df.values.tolist()
print list

output:

输出:

[['Column 1', 'Column 2'], [1L, 2L], [3L, 4L]]

desired output:

所需的输出:

[['Column 1', 'Column 2'], ['Index 1', 1L, 2L], ['Index 2', 3L, 4L]]

回答by Nader Hisham

In [29]:
[df.columns.tolist()] + df.reset_index().values.tolist()
Out[29]:
[['Column 1', 'Column 2'], ['Index 1', 1L, 2L], ['Index 2', 3L, 4L]]

回答by R Nar

add a list comprehension in this line:

在此行中添加列表理解:

list = [df.columns[:,].values.astype(str).tolist()] + [[index] + vals for index,value in zip(df.index.tolist(),df.values.tolist())]

also, because you have your columns in your first item as item[colindex] = column at colindex, I would maybe change: ['Index 1',x1,y1]to [x1,y1,'Index 1']? I dont know if the position of Indexitem matters but this seems to make more sense so that the columns line up? Although I dont know how you are using your data so maybe not :)

另外,因为您的第一个项目中的列是item[colindex] = column at colindex,所以我可能会更改:['Index 1',x1,y1][x1,y1,'Index 1']? 我不知道Index项目的位置是否重要,但这似乎更有意义,以便列对齐?虽然我不知道你是如何使用你的数据的,所以可能不会:)

EDITTED: df.index.tolist()is better than df.index.values.tolist()and i think it returns just items so you need to initialize [index]as a list instead of just index

编辑:df.index.tolist()df.index.values.tolist()我认为它只返回项目更好,所以你需要初始化[index]为一个列表而不是仅仅index