Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Pandas dataframe 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

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]]
like image 870
user2242044 Avatar asked Nov 12 '15 19:11

user2242044


People also ask

How do you convert the index of a DataFrame to a list in Python?

You can use df. index to access the index object and then get the values in a list using df. index. tolist() .

Can pandas index to list?

tolist() function return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period).

How do I convert a pandas series to a list?

To convert a pandas Series to a list, simply call the tolist() method on the series which you wish to convert.


2 Answers

In [29]:
[df.columns.tolist()] + df.reset_index().values.tolist()
Out[29]:
[['Column 1', 'Column 2'], ['Index 1', 1L, 2L], ['Index 2', 3L, 4L]]
like image 167
Nader Hisham Avatar answered Sep 17 '22 17:09

Nader Hisham


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 Index item 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 :)

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

like image 26
R Nar Avatar answered Sep 17 '22 17:09

R Nar