Get a List of Particular Column Values in a Pandas DataFrame
Last Updated :
29 Nov, 2024
In this article, you'll learn how to extract all values of a particular column from a Pandas DataFrame as a Python list.
Get a List of a Particular Column Using tolist()
tolist() method is a simple and effective way to convert a Pandas Series (column) into a Python list. Here's an example:
Python
import pandas as pd
# dictionary
data = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'],
'Marks': [87, 91, 97, 95]}
# create DataFrame
df = pd.DataFrame(data)
# Get the 'Marks' column as a list
marks_list = df['Marks'].tolist()
# Show the list
print("List of 'Marks' Columns: ")
print(marks_list)
OutputList of 'Marks' Columns:
[87, 91, 97, 95]
Apart from tolist() method, there are several other ways to extract the values of a particular column from a Pandas DataFrame as a list:
Get a List Using get() Method
get() method can also be used to extract a column, and you can then convert it to a list using tolist().
Python
import pandas as pd
# dictionary
data = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'],
'Marks': [87, 91, 97, 95]}
# create DataFrame
df = pd.DataFrame(data)
# Get 'Marks' column using get() and convert to list
marks_column = df.get('Marks')
marks_list_using_get = marks_column.tolist()
# Show the list
print("List of 'Marks' Columns: ")
print(marks_list_using_get)
OutputList of 'Marks' Columns:
[87, 91, 97, 95]
Get a List Using .loc[] Method
The .loc[] method allows you to select specific rows and columns. You can use it to extract a column as a list:
Python
import pandas as pd
# dictionary
data = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'],
'Marks': [87, 91, 97, 95]}
# create DataFrame
df = pd.DataFrame(data)
# Use .loc[] to extract 'Marks' column as list
marks_list_using_loc = df.loc[:, 'Marks'].tolist()
# Show the list
print("List of 'Marks' Columns extracted using .loc[]: ")
print(marks_list_using_loc)
OutputList of 'Marks' Columns extracted using .loc[]:
[87, 91, 97, 95]
Get a List Using .values Attribute
values attribute returns a Numpy array, which you can easily convert to a list using the tolist() method:
Python
import pandas as pd
# dictionary
data = {'Name': ['Martha', 'Tim', 'Rob', 'Georgia'],
'Marks': [87, 91, 97, 95]}
# create DataFrame
df = pd.DataFrame(data)
# Use .values to get 'Marks' column as a list
marks_list_using_values = df['Marks'].values.tolist()
# Show the list
print("List of 'Marks' Column")
print(marks_list_using_values)
OutputList of 'Marks' Column
[87, 91, 97, 95]