Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert columns of a pandas DataFrame into a list of lists?

I have a pandas DataFrame with multiple columns.

2u    2s    4r     4n     4m   7h   7v 0     1     1      0      0     0    1 0     1     0      1      0     0    1 1     0     0      1      0     1    0 1     0     0      0      1     1    0 1     0     1      0      0     1    0 0     1     1      0      0     0    1 

What I want to do is to convert this pandas.DataFrame into a list like following

X = [      [0, 0, 1, 1, 1, 0],      [1, 1, 0, 0, 0, 1],      [1, 0, 0, 0, 1, 1],      [0, 1, 1, 0, 0, 0],      [0, 0, 0, 1, 0, 0],      [0, 0, 1, 1, 1, 0],      [1, 1, 0, 0, 0, 1]     ] 

2u 2s 4r 4n 4m 7h 7v are column headings. It will change in different situations, so don't bother about it.

like image 864
naz Avatar asked Feb 27 '13 12:02

naz


People also ask

How do I turn a column into a list in pandas?

values. tolist() you can convert pandas DataFrame Column to List. df['Courses'] returns the DataFrame column as a Series and then use values. tolist() to convert the column values to list.

How do I make a column into a list?

Index column can be converted to list, by calling pandas. DataFrame. index which returns the index column as an array and then calling index_column. tolist() which converts index_column into a list.

Can we convert DataFrame to list?

Dataframe() function to declare the DataFrame from the dictionary and then use the tolist() function to convert the Dataframe to a list containing all the rows of column 'emp_name'. Once you will print 'd' then the output will display in the form of a list.

How do you get a list of all columns 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. After this, we can work with the columns to access certain columns, rename a column, and so on.


1 Answers

It looks like a transposed matrix:

df.values.T.tolist() 

[list(l) for l in zip(*df.values)] 

[[0, 0, 1, 1, 1, 0],  [1, 1, 0, 0, 0, 1],  [1, 0, 0, 0, 1, 1],  [0, 1, 1, 0, 0, 0],  [0, 0, 0, 1, 0, 0],  [0, 0, 1, 1, 1, 0],  [1, 1, 0, 0, 0, 1]] 
like image 103
eumiro Avatar answered Sep 20 '22 14:09

eumiro