Categories: Python

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here !

Pandas provides flexible ways of generating data frames. One of them is by inputting in pd.DataFrame() function. For example, ND1 is a nested dictionary.

ND1= {'age': { 'VB1': 22, 'VB2': 33,'VB3':19},
            'name': { 'VB1': 'wilson', 'VB2': 'shirley', 'VB3': 'mico'},
            'city': { 'VB1': 'molde', 'VB2': 'molde', 'VB3': 'aukra'}}

When this dictionary is passed directly as an argument to the function DataFrame(), it will be treated by Pandas that external keys of the nested dictionary as column names of the new data frame, and internal keys as labels for the indexes. If there are any unmatched fields or inconsistency exist during this process of interpretation, Pandas will add NaN value to those missing places.

#Import Pandas module
import pandas as pd
DF1 = pd.DataFrame(ND1)
DF1
#Output
     age     name   city
VB1   22   wilson  molde
VB2   33  shirley  molde
VB3   19     mico  aukra

In the example above, we can see that keys ‘age’, ‘name’, ‘city’ act as column labels, and keys ‘VB1’, ‘VB2’, ‘VB3’ appear as index labels in the new data frame.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago

How to select elements and show information of a Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago