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

11,677

Solution 1

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

Solution 2

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

Share:
11,677
user2242044
Author by

user2242044

Updated on June 09, 2022

Comments

  • user2242044
    user2242044 almost 2 years

    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]]