Home »
Python »
Python Programs
Python - List of Tuples to DataFrame Conversion
Given a list of tuples, we have to convert it to a pandas dataframe.
Submitted by Pranit Sharma, on August 09, 2022
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Python List and Tuple
A list is a collection of heterogeneous elements and it is mutable. Tuples are also another built-in data type of python used to store heterogeneous elements.
Elements inside the list are encapsulated in square brackets whereas elements inside tuples are encapsulated in normal parenthesis.
Both list and tuples are considered as a series or collection and we can perform operations like insert, update and delete with its elements.
If there are elements in the form of a tuple in a list, it will be called a list of tuples.
Create/convert a list of tuples to pandas dataframe
To create a DataFrame with this list of tuples, we will simply use pandas.DataFrame() method inside which we will pass a list of tuples, but we have to pass a parameter called columns=[] for which we will assign a list of column headers.
Let us understand with the help of an example,
Python program to convert a list of tuples to pandas dataframe
# Importing pandas package
import pandas as pd
# Creating two list of tuples
data = [
('Ram', 'APPLE', 23),
('Shyam', 'GOOGLE', 25),
('Seeta', 'GOOGLE', 22),
('Geeta', 'MICROSOFT', 24),
('Raman', 'GOOGLE', 23),
('Sahil', 'SAMSUNG', 23)
]
# Creating a DataFrame
df = pd.DataFrame(data,columns=['Name','Company','Age'])
# Display DataFrame
print("DataFrame1:\n",df,"\n")
Output
Python Pandas Programs »