How to Convert Pandas DataFrame into a List?
Last Updated :
10 Aug, 2024
In this article, we will explore the process of converting a Pandas DataFrame into a List, We’ll delve into the methods and techniques involved in this conversion, shedding light on the versatility and capabilities of Pandas for handling data structures in Python.
Ways to convert Pandas DataFrame Into a List
There are various methods of converting Pandas DataFrame into a List, we are discussing some generally used methods for converting Pandas DataFrame into a List with an example:
- Pandas DataFrame Column to List
- Pandas DataFrame into Nested List
- Pandas DataFrame into Nested List of columns
- Pandas DataFrame to List with Column Names
Creating a Dataframe in Pandas
First, let’s create a Basic DataFrame:
Python
import pandas as pd
# Creating a dictionary to store data
data = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ],
'Age': [35, 70, 45, 20] }
# Creating DataFrame
df = pd.DataFrame(data)
# Print the dataframe
df
Output :
Name Age
0 Tony 35
1 Steve 70
2 Bruce 45
3 Peter 20
Converting Dataframe into List
At times, you may need to convert your pandas dataframe to List. To accomplish this task, ‘ tolist() ‘ function can be used. Below is a basic example to use this function and convert the required DataFrame into a List.
Python
Output :
[['Tony', 35], ['Steve', 70], ['Bruce', 45], ['Peter', 20]]
Here, Each inner list contains all the columns of a particular row.
Pandas DataFrame can be converted into lists in multiple ways. Let’s have a look at different ways of converting a DataFrame one by one.
Converting Pandas DataFrame Column to List
In this example we convertes column to list below code utilizes Pandas to create a DataFrame from a dictionary containing ‘Name’ and ‘Age’ columns. It then converts the ‘Name’ column of the DataFrame into a list named ‘names’ using the tolist() method. Finally, the code prints the resulting list of names.
Python
import pandas as pd
# Creating a dictionary to store data
data = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] ,
'Age': [35, 70, 45, 20] }
# Creating DataFrame
df = pd.DataFrame(data)
# Converting DataFrame to a list containing
# all the rows of column 'Name'
names = df['Name'].tolist()
# Printing the converted list.
print(names)
Output:
['Tony', 'Steve', 'Bruce', 'Peter']
Converting Pandas DataFrame into Nested List
In this example we converted DataFrame to Nested List below code uses Pandas to create a DataFrame from a dictionary with ‘Name’ and ‘Age’ columns. It initializes an empty list named ‘res’ and iterates through each column of the DataFrame. For each column, the code stores the values of the column in a temporary list (‘li’) and appends this list to ‘res.’ Finally, the code prints the resulting list, which contains lists representing the values of each column in the DataFrame.
Python
import pandas as pd
# Creating a dictionary to store data
data = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] ,
'Age': [35, 70, 45, 20] }
# Creating DataFrame
df = pd.DataFrame(data)
# Creating an empty list
res=[]
# Iterating through the columns of
# dataframe
for column in df.columns:
# Storing the rows of a column
# into a temporary list
li = df[column].tolist()
# appending the temporary list
res.append(li)
# Printing the final list
print(res)
Output:
[['Tony', 'Steve', 'Bruce', 'Peter'], [35, 70, 45, 20]]
Converting Pandas DataFrame into Nested List of columns
In this example we uses df.values.tolist() method for convert dataframe to list as below code utilizes Pandas to create a DataFrame from a dictionary containing ‘Name’ and ‘Age’ columns. It then employs the ‘df.values.tolist()’ method to convert the entire DataFrame into a list (‘li’). The resulting list represents each row of the DataFrame as a sublist, and the code prints this transformed list. This concise approach streamlines the process of converting a DataFrame into a nested list of its values.
Python
import pandas as pd
# Creating a dictionary to store data
data = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] ,
'Age': [35, 70, 45, 20] }
# Creating DataFrame
df = pd.DataFrame(data)
# Converting dataframe to list
li = df.values.tolist()
# Printing list
print(li)
Output :
[['Tony', 35], ['Steve', 70], ['Bruce', 45], ['Peter', 20]]
Converting Pandas DataFrame to List with Column Names
In this example we convert dataframe to list with column name as below code uses Pandas to make a table from a dictionary. It creates a list (‘li’) by putting together column names (converted to a sublist using df.columns.values.tolist()) and the values of the table (df.values.tolist()). So, the list has the names of the columns in the first part, and the rest of the list has the actual information in the table. The code then shows this list, giving both the names of the columns and the data in a clear way.
Python
import pandas as pd
# Creating a dictionary to store data
data = {'Name':['Tony', 'Steve', 'Bruce', 'Peter' ] ,
'Age': [35, 70, 45, 20] }
# Creating DataFrame
df = pd.DataFrame(data)
# Converting dataframe to list
li = [df.columns.values.tolist()] + df.values.tolist()
# Printing list
print(li)
Output:
[['Name', 'Age'], ['Tony', 35], ['Steve', 70], ['Bruce', 45], ['Peter', 20]]
How to Convert Pandas DataFrame into a List? – FAQs
How to Convert Pandas DataFrame to a List?
To convert a pandas DataFrame to a list, you can use several methods depending on the structure you need in the output list. You can convert the entire DataFrame to a list of dictionaries, where each dictionary represents a row, or to a list of lists, where each sublist represents a row.
Example of Converting DataFrame to a List of Dictionaries:
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3],
'B': ['a', 'b', 'c']
})
# Convert DataFrame to a list of dictionaries
list_of_dicts = df.to_dict('records')
print(list_of_dicts) # Output: [{'A': 1, 'B': 'a'}, {'A': 2, 'B': 'b'}, {'A': 3, 'B': 'c'}]
Example of Converting DataFrame to a List of Lists:
# Convert DataFrame to a list of lists
list_of_lists = df.values.tolist()
print(list_of_lists) # Output: [[1, 'a'], [2, 'b'], [3, 'c']]
How Do I Turn a Panda Series into a List?
To convert a pandas Series into a list, you can use the to_list() method or the list() constructor.
Example:
s = pd.Series([1, 2, 3])
# Convert Series to list
series_list = s.to_list()
print(series_list) # Output: [1, 2, 3]
What is to_list()?
The to_list() method in pandas is used to convert a Series or DataFrame column to a list. When called on a Series, it returns the Series elements as a Python list.
Example:
s = pd.Series([1, 2, 3, 4])
result = s.to_list()
print(result) # Outputs: [1, 2, 3, 4]
How to Export Pandas DataFrame to Table?
To export a pandas DataFrame to a table format, you might consider outputting to a CSV file, Excel file, or SQL database, depending on your interpretation of “table”. For textual representation in a Jupyter Notebook or console, you can simply print the DataFrame.
Example of Exporting DataFrame to CSV:
df.to_csv('output.csv', index=False)Example of Displaying DataFrame as a Table in a Notebook:
print(df) # Simply printing the DataFrame
What is the Difference Between a List and a DataFrame?
- List: A list in Python is a collection of items that can be of different data types. It is ordered, changeable, and supports duplicate elements. Lists are part of Python’s standard data types and do not require any external library.
- DataFrame: A DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is similar to a SQL table or an Excel spreadsheet. DataFrames are provided by the pandas library in Python and are designed to handle complex data manipulation and analysis tasks.
- DataFrames allow for operations on the data at a high level, including pivoting, grouping, joining, and filtering, which are more complex with lists.
Similar Reads
How to Convert Pandas DataFrame into a List?
In this article, we will explore the process of converting a Pandas DataFrame into a List, We'll delve into the methods and techniques involved in this conversion, shedding light on the versatility and capabilities of Pandas for handling data structures in Python. Ways to convert Pandas DataFrame In
7 min read
How to Convert a List to a Dataframe in R
We have a list of values and if we want to Convert a List to a Dataframe within it, we can use a as.data.frame. it Convert a List to a Dataframe for each value. A DataFrame is a two-dimensional tabular data structure that can store different types of data. Various functions and packages, such as dat
4 min read
Convert Floats to Integers in a Pandas DataFrame
Let us see how to convert float to integer in a Pandas DataFrame. We will be using the astype() method to do this. It can also be done using the apply() method. Convert Floats to Integers in a Pandas DataFrameBelow are the ways by which we can convert floats to integers in a Pandas DataFrame: Using
3 min read
How to Convert a List to a DataFrame Row in Python?
In this article, we will discuss how to convert a list to a dataframe row in Python. Method 1: Using T function This is known as the Transpose function, this will convert the list into a row. Here each value is stored in one column. Syntax: pandas.DataFrame(list).T Example: C/C++ Code # import panda
3 min read
How to Convert Index to Column in Pandas Dataframe?
Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learni
2 min read
How to convert pandas DataFrame into SQL in Python?
In this article, we aim to convert the data frame into an SQL database and then try to read the content from the SQL database using SQL queries or through a table. Convert Pandas DataFrame into SQL in PythonBelow are some steps by which we can export Python dataframe to SQL file in Python: Step 1: I
4 min read
Convert JSON to Pandas DataFrame
When working with data, it's common to encounter JSON (JavaScript Object Notation) files, which are widely used for storing and exchanging data. Pandas, a powerful data manipulation library in Python, provides a convenient way to convert JSON data into a Pandas data frame. In this article, we'll exp
4 min read
Create a list from rows in Pandas dataframe
Python list is easy to work with and also list has a lot of in-built functions to do a whole lot of operations on lists. Pandas dataframe's columns consist of series but unlike the columns, Pandas dataframe rows are not having any similar association. In this post, we are going to discuss several wa
4 min read
Python - Convert dict of list to Pandas dataframe
In this article, we will discuss how to convert a dictionary of lists to a pandas dataframe. Method 1: Using DataFrame.from_dict() We will use the from_dict method. This method will construct DataFrame from dict of array-like or dicts. Syntax: pandas.DataFrame.from_dict(dictionary) where dictionary
2 min read
Convert dataframe to nested list in R
In R Programming Data frame is nothing but a two-dimensional entity that consists of rows and columns whereas Lists in R are data structures that are able to store multiple data values at once. List Creation Lists in R can be created using list() function. Syntax: list(element1, element2, element3,.
2 min read
Convert a Dataframe Column to Integer in Pandas
Converting DataFrame columns to the correct data type is important especially when numeric values are mistakenly stored as strings. Let's learn how to efficiently convert a column to an integer in a Pandas DataFrame Convert DataFrame Column to Integer - using astype() Methodastype() method is simple
3 min read
How to Convert String to Integer in Pandas DataFrame?
Let's see methods to convert string to an integer in Pandas DataFrame: Method 1: Use of Series.astype() method. Syntax: Series.astype(dtype, copy=True, errors=’raise’) Parameters: This method will take following parameters: dtype: Data type to convert the series into. (for example str, float, int).c
3 min read
How to convert index in a column of the Pandas dataframe?
Each row in a dataframe (i.e level=0) has an index value i.e value from 0 to n-1 index location and there are many ways to convert these index values into a column in a pandas dataframe. First, let's create a Pandas dataframe. Here, we will create a Pandas dataframe regarding student's marks in a pa
4 min read
How to Convert Integers to Floats in Pandas DataFrame?
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to String, String to Integer, etc. There are 2 methods to convert Integers to Floats: Method 1: Using DataFrame.astype() method Syntax : DataFrame.astype(dtype, cop
4 min read
How to Convert Integers to Strings in Pandas DataFrame?
In this article, we'll look at different methods to convert an integer into a string in a Pandas dataframe. In Pandas, there are different functions that we can use to achieve this task : map(str)astype(str)apply(str)applymap(str) Example 1 : In this example, we'll convert each value of a column of
3 min read
Create a list from rows in Pandas DataFrame | Set 2
In an earlier post, we had discussed some approaches to extract the rows of the dataframe as a Python's list. In this post, we will see some more methods to achieve that goal. Note : For link to the CSV file used in the code, click here. Solution #1: In order to access the data of each row of the Pa
2 min read
How to Convert Dataframe column into an index in Python-Pandas?
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a data frame column to row name or index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':[
2 min read
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictio
4 min read
How To Convert Pandas Dataframe To Nested Dictionary
In this article, we will learn how to convert Pandas DataFrame to Nested Dictionary. Convert Pandas Dataframe To Nested DictionaryConverting a Pandas DataFrame to a nested dictionary involves organizing the data in a hierarchical structure based on specific columns. In Python's Pandas library, we ca
2 min read