我有一个 Pandas
数据框,我想将其转换为列表列表,其中每个子列表都是数据框中的一行。我还应该如何包含索引值,以便稍后可以使用 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
输出:
[['Column 1', 'Column 2'], [1L, 2L], [3L, 4L]]
期望的输出:
[['Column 1', 'Column 2'], ['Index 1', 1L, 2L], ['Index 2', 3L, 4L]]
最佳答案
In [29]:
[df.columns.tolist()] + df.reset_index().values.tolist()
Out[29]:
[['Column 1', 'Column 2'], ['Index 1', 1L, 2L], ['Index 2', 3L, 4L]]
关于python - 将 Pandas 数据框转换为包含索引、数据和列的列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33679729/