Python Pandas - 将嵌套字典转换成多索引数据帧
首先,让我们创建一个嵌套字典 −
dictNested = {'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'],'Country': ['India', 'Australia', 'England']},'Football': {'Boards': ['TFA', 'TCSA', 'GFA'],'Country': ['England', 'Canada', 'Germany']
}}现在,创建一个空字典 −
new_dict = {}现在,循环分配值 −
for outerKey, innerDict in dictNested.items():
for innerKey, values in innerDict.items():
new_dict[(outerKey, innerKey)] = values
转换为多索引数据帧 −
pd.DataFrame(new_dict)
示例
以下是代码 −
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)输出
这将生成以下输出 −
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP