Monday, November 18, 2024
Google search engine
HomeLanguagesCreate Pandas Dataframe from Dictionary of Dictionaries

Create Pandas Dataframe from Dictionary of Dictionaries

In this article, we will discuss how to create a pandas dataframe from the dictionary of dictionaries in Python.

Method 1: Using DataFrame()

We can create a dataframe using Pandas.DataFrame() method.

Syntax:

pandas.DataFrame(dictionary)

where

  • pandas are the module that supports DataFrame data structure
  • DataFrame is the datastructure that converts dictionary into dataframe
  • dictionary is the input dictionary

Example: Create pandas Dataframe from the dictionary of dictionaries.

Python3




# import pandas module
import pandas
  
# create student dictionary of dictionaries 
# with 3 students with Age and address
data = {'Ojaswi': {'Age': 15, 'Address': 'Hyderabad'},
        'Rohith':  {'Age': 9, 'Address': 'Hyderabad'},
        'Gnanesh':  {'Age': 15, 'Address': 'Guntur'}}
  
# create pandas dataframe from dictionary of 
# dictionaries
data = pandas.DataFrame(data)
  
# display
print(data)


Output:

Example 2: Example: Create pandas Dataframe from the dictionary of dictionaries.

Python3




# import pandas module
import pandas
  
# create student dictionary of dictionaries with
# 5 students with Age ,subject and  address
data = {'Ojaswi': {'Age': 15, 'subject': 'java', 'Address': 'Hyderabad'},
        'Rohith':  {'Age': 9, 'subject': 'python', 'Address': 'Hyderabad'},
        'Gnanesh':  {'Age': 15, 'subject': 'c/c++', 'Address': 'Guntur'},
        'divya':  {'Age': 21, 'subject': 'html', 'Address': 'ponnur'},
        'ramya':  {'Age': 15, 'subject': 'c/c++', 'Address': 'delhi'}}
  
# create pandas dataframe from dictionary of
# dictionaries
data = pandas.DataFrame(data)
  
# display
data


Output:

Method 2: Using from_dict()

from_dict() is used to convert the dataframe from the dictionary 

Syntax:

pandas.DataFrame.from_dict(dictionary)

Where, dictionary is the input dictionary of dictionaries

Example: Create pandas Dataframe from dictionary of dictionaries.

Python3




# import pandas module
import pandas
  
# create student dictionary of dictionaries with 3 
# students with Age and address
data = {'Ojaswi': {'Age': 15, 'Address': 'Hyderabad'},
        'Rohith':  {'Age': 9, 'Address': 'Hyderabad'},
        'Gnanesh':  {'Age': 15, 'Address': 'Guntur'}}
  
# create pandas dataframe from dictionary of dictionaries 
# using from_dict() method
data = pandas.DataFrame.from_dict(data)
  
# display
data


Output:

RELATED ARTICLES

Most Popular

Recent Comments