Convert Pandas Column to List
In data analysis and manipulation, we often need to convert a column of a dataframe to a list. For example, getting column values as a list to use it in some other function or to perform some operations on it.
In this article, we will look at multiple different ways to convert a column of a dataframe to a list.
- Using tolist() Method
- Converting via values Attribute
- List Comprehension Approach
- Using tolist() with Specific Column Selection
- Conclusion
Table of Contents
1. Using tolist() Method
To list method is a built-in method in pandas that convert a given column of dataframe to a list.
First access the column you want to convert to a list and then call the tolist() method on it.
import pandas as pd
# Sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# 👇 Converting 'Name' column to a list
name_list = df['Name'].tolist()
print(name_list)
Output:
['Alice', 'Bob', 'Charlie']
2. Converting via values Attribute
An alternative method involves using the values attribute of the Pandas Series, which returns a NumPy array. You can then convert this array to a Python list.
import pandas as pd
# Sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# 👇 Converting 'Name' column to a list
name_list = df['Name'].values.tolist()
print(name_list)
Output:
['Alice', 'Bob', 'Charlie']
3. List Comprehension Approach
List comprehension is a quick way to create list in Python. To convert a column of a dataframe to a list, we can use list comprehension.
Here is how we can do it:
import pandas as pd
# Sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# 👇 Converting 'Name' column to a list
name_list = [name for name in df['Name']]
print(name_list)
Output:
['Alice', 'Bob', 'Charlie']
4. Using tolist() with Specific Column Selection
If you have multiple columns and want to convert a specific one, you can use the iloc or loc indexer along with tolist().
import pandas as pd
# Sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'San Francisco', 'Los Angeles']}
df = pd.DataFrame(data)
# 👇 Converting 'City' column to a list using iloc
city_list = df.iloc[:, 2].tolist()
print(city_list)
Output:
['New York', 'San Francisco', 'Los Angeles']
Conclusion
Now you know how to convert a column of a dataframe to a list in Python and you can choose the method that suits your needs.
Whether it's using the tolist() method directly, utilizing the values attribute, employing list comprehension for a concise approach, or selecting a specific column with iloc or loc, Pandas provides versatile options for converting columns to lists.