Pandas: How to Quickly Convert Column to List


You can use one of the following methods to convert a column in a pandas DataFrame to a list:

Method 1: Use tolist()

df['my_column'].tolist()

Method 2: Use list()

list(df['my_column'])

Both methods will return the exact same result.

The following examples show how to use each of these methods with the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B'],
                   'points': [99, 90, 93, 86, 88, 82],
                   'assists': [33, 28, 31, 39, 34, 30]})

#view DataFrame
print(df)

  team  points  assists
0    A      99       33
1    A      90       28
2    A      93       31
3    B      86       39
4    B      88       34
5    B      82       30

Method 1: Convert Column to List Using tolist()

The following code shows how to use the tolist() function to convert the ‘points’ column in the DataFrame to a list:

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

#view list
print(my_list)

[99, 90, 93, 86, 88, 82]

We can confirm that the result is a list by using the type() function:

#check data type
type(my_list)

list

Method 2: Convert Column to List Using list()

The following code shows how to use the list() function to convert the ‘points’ column in the DataFrame to a list:

#convert column to list
my_list = list(df['points'])
#view list
print(my_list)

[99, 90, 93, 86, 88, 82]

We can confirm that the result is a list by using the type() function:

#check data type
type(my_list)

list

Notice that both methods return the exact same results.

Note that for extremely large DataFrames, the tolist() method tends to perform the fastest.

Additional Resources

The following tutorials explain how to perform other common functions with columns of a pandas DataFrame:

How to Drop Columns in Pandas
How to Exclude Columns in Pandas
How to Apply a Function to Selected Columns in Pandas
How to Change the Order of Columns in Pandas DataFrame

Leave a Reply

Your email address will not be published.