In this post, you’ll learn how to convert a Pandas column to a list, enabling you to also convert a Pandas series into a list.
You’ll learn how to use the Pandas .tolist()
method, the Python list()
function, and the numpy .tolist()
method.
Table of Contents
Loading a Sample Dataframe
Let’s start off by loading a sample dataframe. Copy the code below if you wanted to follow along with this tutorial.
import pandas as pd
df = pd.DataFrame.from_dict(
{
'Name': ['Jim', 'Carl', 'Amy', 'Anne'],
'Age': [23, 45, 35, 19],
'Birth City': ['Montreal', 'Paris', 'Toronto', 'Chicago'],
'Gender': ['M', 'M', 'F', 'F']
}
)
print(df)
This returns the following dataframe:
Name Age Birth City Gender
0 Jim 23 Montreal M
1 Carl 45 Paris M
2 Amy 35 Toronto F
3 Anne 19 Chicago F
Now let’s get started converting our dataframe column to a list!
Learn how to convert a list to a string in Python by checking out my tutorial here: Learn How to Convert a List to a String in Python.
Pandas Column to List – Pandas tolist Method
First, we’ll use the Pandas .tolist()
method to convert our Pandas series to a list. The advantage here is that we don’t need to import numpy if we’re not using it for anything else.
The Pandas .tolist()
method acts on a Pandas series (column) and converts it to a list.
As an example, let’s take our name column and convert it to a list:
>>> names = df['Name'].tolist()
>>> print(names)
['Jim', 'Carl', 'Amy', 'Anne']
We can see here that a list names
has been returned which contains the various values in that column.
Pandas Series to List – Python list() function
Similar to the example above, the we can use Python’s built-in list()
function to convert a Pandas series to a list.
Instead of appending the function as a method to a Pandas series, what we’ll do is wrap the column in the list()
function.
In the below example, let’s convert the Birth City
column to a list:
>>> cities = list(df['Birth City'])
>>> print(cities)
['Montreal', 'Paris', 'Toronto', 'Chicago']
Similar to using the Pandas .tolist()
method, the built-in list()
function returns a list from a Pandas column.
Pandas Column to List using Numpy
As the last method covered in this tutorial, you’ll learn how to use the numpy .tolist()
method.
We’ll first convert the Pandas series into a numpy array by using the .values
attribute. Then we’ll call the .tolist()
method to return a list.
For this final example, let’s convert the Age column to a list:
>>> ages = df['Age'].values.tolist()
>>> print(ages)
[23, 45, 35, 19]
Conclusion
In this post you learned how to convert a Pandas column to a list, allowing you also to convert a Pandas series to a list. You learned how to do this using the Pandas tolist()
method, the Python list()
function, and the numpy .tolist()
method.
To learn more about the Pandas tolist()
method, check out the official documentation here. To learn more about the Python list()
function, check out the official documentation here.