Convert DataFrame To List – pd.df.values.tolist()

So you want to change your nicely formatted DataFrame to a list of lists? Maybe you’re trying to get it ready for another Data Science package that doesn’t recognize pandas DataFrames.


Pseudo Code: With your DataFrame’s values, change them into a list of lists.

Pandas DataFrame To List

Pandas DataFrame To List - Convert your dataframe to a list by first turning it into a numpy array

.tolist() Parameters


Now the fun part, let’s take a look at a code sample

In [1]:
import pandas as pd

Pandas DataFrame To List

Converting your data from a dataframe to a list of lists can be helpful when working with other libraries. We don't use it too often, but it is a simple operation.

Examples we'll run through:

  1. Converting a DataFrame to a list
  2. Converting a Series to a list

First let's create a DataFrame

In [2]:
df = pd.DataFrame([('Foreign Cinema', 'Restaurant', 289.0),
                   ('Liho Liho', 'Restaurant', 224.0),
                   ('500 Club', 'bar', 80.5),
                   ('The Square', 'bar', 25.30)],
           columns=('name', 'type', 'AvgBill')
0Foreign CinemaRestaurant289.0
1Liho LihoRestaurant224.0
2500 Clubbar80.5
3The Squarebar25.3

1. Converting a DataFrame to a list

In order to convert a DataFrame to a list we first need to extract the 'values' from the DataFrame. The old way of doing this was done via df.values() however Pandas now recommends using .to_numpy() instead.

We'll get an error if we try calling .tolist() right on the DataFrame.

In [3]:
except AttributeError:
    print ("You have an error")
You have an error

So we turn the DataFrame into a numpy array first with .to_numpy()

In [4]:
array([['Foreign Cinema', 'Restaurant', 289.0],
       ['Liho Liho', 'Restaurant', 224.0],
       ['500 Club', 'bar', 80.5],
       ['The Square', 'bar', 25.3]], dtype=object)
In [5]:
[['Foreign Cinema', 'Restaurant', 289.0],
 ['Liho Liho', 'Restaurant', 224.0],
 ['500 Club', 'bar', 80.5],
 ['The Square', 'bar', 25.3]]

2. Converting a Series to a list

Next up is converting a series to a list. This time we don't have to call .to_numpy() on our series.

In [6]:
['Foreign Cinema', 'Liho Liho', '500 Club', 'The Square']

Link to code above

Check out more Pandas functions on our Pandas Page

Official Documentation (note this is for Series.tolist())