36

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
naz
  • 437
  • 1
  • 5
  • 8
  • For anyone who stumbles upon this question in the future: If your data is similar to the one in the OP, a seemingly homogenous grid/array structure, a Pandas DataFrame may not be the right choice of data structure. A NumPy array is probably more appropriate, or even just a plain Python list. – AMC Jan 07 '20 at 16:21
  • 1
    Does this answer your question? [Pandas DataFrame to List of Lists](https://stackoverflow.com/questions/28006793/pandas-dataframe-to-list-of-lists) – AMC Jan 07 '20 at 17:25

2 Answers2

73

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]]
cs95
  • 379,657
  • 97
  • 704
  • 746
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 34
    This returns a list of a list. A ``list(df.values.flatten())`` does the job. – pms Dec 16 '13 at 15:24
  • 2
    @pms By looking at the OPs desired output it indeed looks like they want to create a list of lists. But you could probably convert your comment to answer as it could get deleted by some silly flag. Also, I personally found your comment very useful as I was looking for the single list option. Finally, this could be probably modified to `list(df.values.T.flatten())` so the values will be kept by column. – David Arenburg Mar 26 '17 at 08:25
  • @pms, very good. You can also get a list with `df.values.flatten().tolist()` Note: Google takes you here whether you want a list of list or whether you want to avoid a list of list: I wanted to avoid a list of list and `.flatten()` was the way. – PatrickT Nov 11 '21 at 09:01
2

To change Dataframe into list use tolist() function to convert Let use say i have Dataframe df

to change into list you can simply use tolist() function

df.values.tolist()

You can also change a particular column in to list by using

df['column name'].values.tolist()