79

I have a pandas data frame like this:

admit   gpa  gre  rank   
0  3.61  380     3  
1  3.67  660     3  
1  3.19  640     4  
0  2.93  520     4

Now I want to get a list of rows in pandas like:

[[0,3.61,380,3], [1,3.67,660,3], [1,3.19,640,4], [0,2.93,520,4]]   

How can I do it?

cs95
  • 379,657
  • 97
  • 704
  • 746
user2806761
  • 2,777
  • 3
  • 17
  • 7

3 Answers3

132

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]
cs95
  • 379,657
  • 97
  • 704
  • 746
EdChum
  • 376,765
  • 198
  • 813
  • 562
31

you can do it like this:

map(list, df.values)
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
  • 3
    I'll add a bit of warning to this answer. In Python 3, `map()` returns an iterator so the answer there becomes `list(map(list, df.values))` which is overkill since the shorter spelling `df.values.tolist()` exists. (Another thing to note is that as of pandas 0.24.0 (January 2018), they recommend spelling `df.values` as `df.to_numpy()`, so I suppose it becomes `df.to_numpy().tolist()`. In its favor it does make it explicit that `df.values` gives an unwrapped numpy object and `.tolist()` should be looked up in the numpy docs.) – Steven Rumbalski Jul 02 '19 at 14:39
12

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()
Daan
  • 940
  • 10
  • 22
  • 1
    Note the question asks for a list of lists, so if a multidimensional array isn't good enough adding a `.tolist()` at the end completes it. `df.to_numpy().tolist()` – Steven Rumbalski Jul 02 '19 at 14:44