Convert dataframe column to list
In this post, you will learn how to convert Python dataframe column to list.
A DataFrame is a tabular-like data structure containing an ordered collection of columns. Each column can be of different data types, like numeric, boolean, strings, etc. It has both a row and a column index. It is basically used for analytical purposes.
A list is an arranged collection of elements. It is used to store collections of data. It can contain a list of various types of data objects with a comma separated and enclosed within a square bracket. It is mutable, which means we can change the order of elements. Individual elements can even be replaced after the list has been created. This is one of the leading reasons why lists are being widely used. Lists play an effective role in small projects as they consume more memory. Here, we have mentioned different ways to convert a dataframe to a list.
Python program to convert dataframe column to list using to_list()
In the given example, we have defined a dataframe from a dictionary of lists containing students data. With the help of to_list() method, we have converted the dataframe 'name' column to list.
import pandas as pd
# dictionary of lists
stu_dict = {'Name': ["Smith", "Priska", "Kashyap", "Andy"]
,'Subject': ["Phy", "Maths", "Chm", "Bio"],
'Marks': [90, 99, 92, 89]}
# Create a DataFrame object
student_df = pd.DataFrame(stu_dict, columns=['Name', 'Subject', 'Marks'])
print(student_df)
list_of_names = student_df['Name'].to_list()
print('List of Names: ', list_of_names)
print('Type of listOfNames: ', type(list_of_names))
Output of the above code:
Name Subject Marks
0 Smith Phy 90
1 Priska Maths 99
2 Kashyap Chm 92
3 Andy Bio 89
List of Names: ['Smith', 'Priska', 'Kashyap', 'Andy']
Type of listOfNames: <class 'list'>
Python program to convert dataframe column to list using list()
We can also use the list() function to convert a DataFrame column to a list.
stu_dict = {'Name': ["Smith", "Priska", "Kashyap", "Andy"]
,'Subject': ["Phy", "Maths", "Chm", "Bio"],
'Marks': [90, 99, 92, 89]}
print("Pandas DataFrame:\n\n",stu_dict,"\n")
list_of_subject = list(stu_dict['Subject'])
print("List of Subjects:\n",
list_of_subject,
"\n",
type(list_of_subject))
Output of the above code:
List of Subjects:
['Phy', 'Maths', 'Chm', 'Bio']
<class 'list'>
Related Articles
Convert Python list to numpy arrayConvert string to list Python
Python program to list even and odd numbers of a list
Python loop through list
Sort list in descending order Python
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Python for loop index
Convert List to Dataframe Python
numpy random choice
Dictionary inside list python
Check if list is empty Python
Python raise keyword
Python program to get the largest number from a list
Python program to map two lists into a dictionary