Pandas DataFrame - Convert column to list


Pandas DataFrame - Convert column to list

To convert column of a DataFrame to a list in Python Pandas, get the column of the DataFrame using square bracket notation which returns a Series object, and then call tolist() method on this series object to get the list.

The expression to convert the column 'A' of the DataFrame df to a list is

df['A'].tolist()

This expression returns the column specified by column name, as a Python list.

In this tutorial, we will go through an example, with step by step explanation of how to convert a column of DataFrame to a list.

Example

1. Get column 'A' of DataFrame as list using tolist() in Pandas

In this example, we are given a DataFrame in df_input with columns 'A', 'B', and 'C'. We have to get the column 'A' of this DataFrame as list.

Steps

  1. Given a DataFrame in df_input with specific index.
df_input = pd.DataFrame({
    'A': [2, 4, 6],
    'B': [1, 3, 5]})
  1. Get the column 'A' from the DataFrame df_input using square bracket notation.
df_input['A']
  1. The above expression returns the column as a Series object. Call tolist() method on this series object, and the method returns the series object as a list.
df_input['A'].tolist()
  1. In total, the above expression returns the column 'A' in the DataFrame as a list. You may store it in a variable, say column_A_list, and also print it to output.
column_A_list = df_input['A'].tolist()

Program

The complete program to convert the specified column in the DataFrame to a list.

Python Program

import pandas as pd

# Take a DataFrame
df_input = pd.DataFrame({
    'A': [2, 4, 6],
    'B': [1, 3, 5]})

# Get column A as list
column_A_list = df_input['A'].tolist()
print(column_A_list)

Output

[2, 4, 6]

Summary

In this Pandas Tutorial, we learned how to convert the column in DataFrame to a list using Series tolist() method, with examples.