Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas dataframe to a list

Tags:

python

pandas

I have a pandas dataframe:

apple   banana  carrot  diet coke
1         1       1         0
0         1       0         0
1         0       0         0
1         0       1         1
0         1       1         0
0         1       1         0

I would like to convert this to the following:

[['apple', 'banana', 'carrot'],
 ['banana'],
 ['apple'],
 ['apple', 'carrot', 'diet coke'],
 ['banana', 'carrot'],
 ['banana', 'carrot']]

How can I do it? Thanks a lot.

like image 688
kevin Avatar asked Dec 04 '15 04:12

kevin


People also ask

How do you convert a column in a DataFrame to a list?

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.

Can you store DataFrame in a list?

Pandas DataFrame can be converted into lists in multiple ways. Let's have a look at different ways of converting a DataFrame one by one. Method #1: Converting a DataFrame to List containing all the rows of a particular column: Python3.


1 Answers

Because life is short, I might do something straightforward like

>>> fruit = [df.columns[row.astype(bool)].tolist() for row in df.values]
>>> pprint.pprint(fruit)
[['apple', 'banana', 'carrot'],
 ['banana'],
 ['apple'],
 ['apple', 'carrot', 'diet coke'],
 ['banana', 'carrot'],
 ['banana', 'carrot']]

This works because we can use a boolean array (row.astype(bool)) to select only the elements of df.columns where the row has True.

like image 68
DSM Avatar answered Sep 20 '22 13:09

DSM