Creating a Pandas DataFrame using Dict of Tuples in Python
Working with Python dictionaries containing tuples is a common scenario, especially when dealing with heterogeneous data. Transforming this data into a Pandas DataFrame allows for efficient manipulation and analysis. In this article, we will see how we can convert a dictionary with a tuple into a DataFrame in Python.
Convert Dictionary with Tuple into a DataFrame in Python
Below are the different ways by which we can convert dictionary with tuple into a DataFrame in Python:
- Using pandas.DataFrame.from_dict()
- Using pandas.DataFrame()
- Using List Comprehension
Using pandas.DataFrame.from_dict() Method
In this example, a Python dictionary data
with keys ‘A’ and ‘B’, each containing a list of tuples, is converted into a DataFrame using the from_dict()
method from the Pandas library. The resulting Pandas DataFrame df
is then printed, creating a tabular representation of the nested tuples.
Python3
import pandas as pd # Sample dictionary data = { 'A' : [( 1 , 'x' ), ( 2 , 'y' ), ( 3 , 'z' )], 'B' : [( 4 , 'p' ), ( 5 , 'q' ), ( 6 , 'r' )]} # Convert dictionary to DataFrame df = pd.DataFrame.from_dict(data, orient = 'index' ).transpose() print (df) |
Output:
A B
0 (1, x) (4, p)
1 (2, y) (5, q)
2 (3, z) (6, r)
Using pandas.DataFrame() Method
In this example, a Python dictionary data
with keys ‘A’ and ‘B’, each containing a list of tuples, is directly converted into a DataFrame using the Pandas library. The resulting DataFrame df
is then printed, generating a tabular structure where each tuple is expanded into separate columns.
Python3
import pandas as pd # Sample dictionary data = { 'A' : [( 1 , 'x' ), ( 2 , 'y' ), ( 3 , 'z' )], 'B' : [( 4 , 'p' ), ( 5 , 'q' ), ( 6 , 'r' )]} # Convert dictionary to DataFrame df = pd.DataFrame(data) print (df) |
Output:
A B
0 (1, x) (4, p)
1 (2, y) (5, q)
2 (3, z) (6, r)
Using List Comprehension
In this example, the original Python dictionary data_dict
with keys ‘Key1’, ‘Key2’, and ‘Key3’, each containing a tuple, is converted into a DataFrame using list comprehension and the Pandas library. The resulting DataFrame df
is then printed, showcasing a tabular structure where each tuple’s elements are expanded into separate columns (‘Column1’ and ‘Column2’) with the dictionary keys as the index.
Python3
import pandas as pd # Original dictionary with tuples data_dict = { 'Key1' : ( 'A' , 10 ), 'Key2' : ( 'B' , 20 ), 'Key3' : ( 'C' , 30 )} # Creating a DataFrame using list comprehension df = pd.DataFrame([(key,) + values for key, values in data_dict.items()], columns = [ 'Index' , 'Column1' , 'Column2' ]).set_index( 'Index' ) # Displaying the DataFrame print (df) |
Output:
Column1 Column2
Index
Key1 A 10
Key2 B 20
Key3 C 30
Contact Us