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]]
You can use df. index to access the index object and then get the values in a list using df. index. tolist() .
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).
To convert a pandas Series to a list, simply call the tolist() method on the series which you wish to convert.
In [29]:
[df.columns.tolist()] + df.reset_index().values.tolist()
Out[29]:
[['Column 1', 'Column 2'], ['Index 1', 1L, 2L], ['Index 2', 3L, 4L]]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With