How to Convert a DataFrame to a List in Pandas


Occasionally you may need to convert a pandas DataFrame to a list in Python. Fortunately this is easy to do so using the pandas tolist() function.

This tutorial illustrates several ways to use this function on the following DataFrame:

import numpy as np
import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
                   'assists': [5, 7, 7, 9, 12],
                   'rebounds': [11, 8, 10, 6, 6]})

#view DataFrame
df


        points	assists	rebounds
0	25	5	11
1	12	7	8
2	15	7	10
3	14	9	6
4	19	12	6

Example 1: Convert Entire DataFrame to List

The following code shows how to convert an entire DataFrame to a list:

#convert entire DataFrame to list
df.values.tolist()

[[25, 5, 11], [12, 7, 8], [15, 7, 10], [14, 9, 6], [19, 12, 6]]

The following code shows how to include the column names in the list:

#convert DataFrame to list and include column names in list
[df.columns.values.tolist()] + df.values.tolist()

[['points', 'assists', 'rebounds'],
 [25, 5, 11],
 [12, 7, 8],
 [15, 7, 10],
 [14, 9, 6],
 [19, 12, 6]]

Example 2: Convert a Single Column in a DataFrame to a List

The following code shows how to convert a single column in a DataFrame to a list:

#convert 'points' column to list
df['points'].tolist()

[25, 12, 15, 14, 19]

The following code shows how to append an item to a list:

#convert 'points' column to list
points = df['points'].tolist()

#append value to end of list
points.append(7)

#view list
points

[25, 12, 15, 14, 19, 7]

You can find more Python tutorials here.

Leave a Reply

Your email address will not be published. Required fields are marked *