Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a list from a pandas DataFrame with the column name and column values?

Tags:

python

pandas

I have a pandas dataframe object that looks like this:

   one  two  three  four  five
0    1    2      3     4     5
1    1    1      1     1     1

I'd like to generate a list of lists objects where the first item is the column label and the remaining list values are the column data values:

nested_list = [['one', 1, 1]
               ['two', 2, 1]
               ['three', 3, 1]
               ['four', 4, 1]
               ['five', 5, 1]]

How can I do this? Thanks for the help.

like image 737
turtle Avatar asked Aug 04 '12 19:08

turtle


2 Answers

Simplest way is probably list(dt.T.itertuples()) (where dt is your dataframe). This generates a list of tuples.

like image 126
BrenBarn Avatar answered Oct 09 '22 01:10

BrenBarn


@BrenBarn answer above yields a list of tuples not a list of list as asked in question. I specifically needed a list of lists to be able to write the dataframe into spreadsheed using DataNitro. Adapted the above example with list comprehension:

[list(x) for x in dt.T.itertuples()]

This yields the result as needed

like image 44
Joop Avatar answered Oct 09 '22 00:10

Joop