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

Python Machine Learning Source Files

Click here to download Python Machine Learning Source Files !

6 days ago

Install PyTorch on Windows

PyTorch is a deep learning package for machine learning, or deep learning in particular for…

2 weeks ago

Topic Modeling using Latent Dirichlet Allocation with Python

Topic modeling is a subcategory of unsupervised machine learning method, and a clustering task in…

1 month ago

Document sentiment classification using bag-of-words in Python

For online Python training registration, click here ! Sentiment classification is a type of machine…

1 month ago

Download R Course source files

Click here to download R Course source files !

10 months ago

Download Python Course source files

Click here to download Python Course Source Files !

10 months ago