Convert Column of pandas DataFrame to List in Python (Example Code)

In this Python tutorial you’ll learn how to transform rows and columns in a pandas DataFrame to a list object.

Setting up the Example

import pandas as pd                       # Import pandas library to Python
my_df = pd.DataFrame({'A':range(2, 8),    # Construct pandas DataFrame
                      'B':['x', 'y', 'y', 'y', 'x', 'x'],
                      'C':range(1, 7)})
print(my_df)
#    A  B  C
# 0  2  x  1
# 1  3  y  2
# 2  4  y  3
# 3  5  y  4
# 4  6  x  5
# 5  7  x  6

Example: Convert pandas DataFrame Column to List Object Using tolist() Function

my_lst = my_df['B'].tolist()              # Convert column to list
print(my_lst)
# ['x', 'y', 'y', 'y', 'x', 'x']

Further Resources & Related Tutorials

Have a look at the following Python tutorials. They explain topics such as variables, lists, and data conversion.

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top