In this article, we will discuss different ways to convert a dataframe column into a list.

Fits of all, create a dataframe object that we are going to use in this example,

Output:

Now how to fetch a single column out of this dataframe and convert it to a python list?

There are different ways to do that, lets discuss them one by one.

Convert a Dataframe column into a list using Series.to_list()

To turn the column ‘Name’ from the dataframe object student_df to a list in a single line,

Output

What did happen here?

How did it work?

Let’s break down the above line into steps,

Step 1: Fetch a column as series

Select the column ‘Name’ from the dataframe using [] operator,

Output:

It returns a Series object names, and we have confirmed that by printing its type.

Step 2 : Convert the Series object to the list

Series class provides a function Series.to_list(), which returns the contents of Series object as list. Use that to convert series names into a list i.e.

Output:

This is how we converted a dataframe column into a list.

Important Note:

It might be possible that it gives you an error i.e.

If you get that error, then please check your Pandas version, you may be using pandas version less than 24.

Upgrade you pandas to the latest version using the following command,

Convert a Dataframe column into a list using numpy.ndarray.tolist()

Another way is converting a Dataframe column into a list is,

Output

We converted the column ‘Name’ into a list in a single line. Let’s see what happened inside it,

How did it work?

Let’s break down the above line into steps,

Step 1: Select a column as a Series object

Select the column ‘Name’ from the dataframe using [] operator,

It returns a Series object.

Step 2: Get a Numpy array from a series object using Series.Values

Output:

Names is a numpy array, and we confirmed it by printing its types.

Step 3: Convert a Numpy array into a list

Numpy array provides a function tolist() to convert its contents to a list,

Output:

This is how we selected our column ‘Name’ from Dataframe as a Numpy array and then turned it to a list.

The complete example is as follows,

Output:

Python Resources

C++11 / C++14 Resources

Design Patterns Resources

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,