Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame to lists of lists including headers

Say I have a DataFrame that looks like this:

df = pd.DataFrame([[1, 2, 3], 
                   [4, 5, 6], 
                   [7, 8, 9]], 
                   columns=['Col 1', 'Col 2', 'Col 3'])
>>> df
   Col 1  Col 2  Col 3
0      1      2      3
1      4      5      6
2      7      8      9

Is there a Pandas way of returning the DataFrame as a list of lists with the headers included?

I can return the headers and values as lists as follows

>>> df.columns.values.tolist()
['Col 1', 'Col 2', 'Col 3']
>>> df.values.tolist()
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> df.tolist()

But how could I return the following result?

[['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 493
ScottMcC Avatar asked Mar 08 '18 15:03

ScottMcC


People also ask

Can I convert DataFrame to list?

In Python tolist() function is used to convert a DataFrame to a list and this function can be used in the below example and convert the required DataFrame into a list of strings. This function always returns a list of the values.

How do you convert a DataFrame to a list tuple?

Method 1: Using collect() method By converting each row into a tuple and by appending the rows to a list, we can get the data in the list of tuple format. Example: Converting dataframe into a list of tuples.

How do I get a list of column names in a DataFrame?

To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe.

How do I get a list of columns in pandas?

You can get the column names from pandas DataFrame using df. columns. values , and pass this to python list() function to get it as list, once you have the data you can print it using print() statement.


2 Answers

Use double transpose with reset_index:

print (df.T.reset_index().values.T.tolist())
[['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

Or nicer insert:

a = df.columns.values.tolist()
b = df.values.tolist()

b.insert(0, a)
print (b)
[['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 81
jezrael Avatar answered Dec 02 '22 15:12

jezrael


You have two lists, so using:

[df.columns.values.tolist()] + df.values.tolist()
>>> [['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 40
patricio Avatar answered Dec 02 '22 13:12

patricio