How to create a pandas DataFrame using a list of tuples?


The pandas DataFrame constructor will create a pandas DataFrame object using a python list of tuples. We need to send this list of tuples as a parameter to the pandas.DataFrame() function.

The Pandas DataFrame object will store the data in a tabular format, Here the tuple element of the list object will become the row of the resultant DataFrame.

Example

# importing the pandas package
import pandas as pd

# creating a list of tuples
list_of_tuples = [(11,22,33),(10,20,30),(101,202,303)]

# creating DataFrame
df = pd.DataFrame(list_of_tuples, columns= ['A','B','C'])

# displaying resultant DataFrame
print(df)

Explanation

In the above example, we have a list with 3 tuple elements and each tuple is having again 3 integer elements, we pass this list object as data to the DataFrame constructor. Then it will create a DataFrame object with 3 rows and 3 columns.

A list of characters is given to the columns parameter, it will assign those characters as column labels of the resultant DataFrame.

Output

      A     B    C
0    11    22    33
1    10    20    30
2   101   202   303

The resultant DataFrame object can be seen in the above output block with 3 rows and 3 columns, and the column label representation is A, B, C.

Example

# importing the pandas package
import pandas as pd

# creating a list of tuples
list_of_tuples = [('A',65),('B',66),('C',67)]

# creating DataFrame
df = pd.DataFrame(list_of_tuples, columns=['Char', 'Ord'])

# displaying resultant DataFrame
print(df)

Explanation

In this following example, we have created a simple pandas DataFrame object using the list of tuples and each tuple has a character and an integer value.

Output

 Char  Ord
0   A   65
1   B   66
2   C   67

The output DataFrame is created by using the list of tuples in the above block, the column labels are ‘Char, Ord’, and the data is taken from tuple elements.

Updated on: 17-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements