- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
At first, let us create a Nested Dictionary −
dictNested = {'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'],'Country': ['India', 'Australia', 'England']},'Football': {'Boards': ['TFA', 'TCSA', 'GFA'],'Country': ['England', 'Canada', 'Germany'] }}
Now, create an Empty Dictionary −
new_dict = {}
Now, loop to assign values −
for outerKey, innerDict in dictNested.items(): for innerKey, values in innerDict.items(): new_dict[(outerKey, innerKey)] = values
Convert to Multi-index DataFrame −
pd.DataFrame(new_dict)
Example
Following is the code −
import pandas as pd # Create Nested dictionary dictNested = {'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'],'Country': ['India', 'Australia', 'England']},'Football': {'Boards': ['TFA', 'TCSA', 'GFA'],'Country': ['England', 'Canada', 'Germany'] }} print"\nNested Dictionary...\n",dictNested new_dict = {} for outerKey, innerDict in dictNested.items(): for innerKey, values in innerDict.items(): new_dict[(outerKey, innerKey)] = values # converting to multiindex dataframe print"\nMulti-index DataFrame...\n",pd.DataFrame(new_dict)
Output
This will produce the following output −
Nested Dictionary... {'Cricket': {'Country': ['India', 'Australia', 'England'], 'Boards': ['BCCI', 'CA', 'ECB']}, 'Football': {'Country': ['England', 'Canada', 'Germany'], 'Boards': ['TFA', 'TCSA', 'GFA']}} Multi-index DataFrame... Cricket Football Boards Country Boards Country 0 BCCI India TFA England 1 CA Australia TCSA Canada 2 ECB England GFA Germany
Advertisements