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)
更多Pandas文章,请阅读:Pandas教程
示例
代码如下
import pandas as pd
# 创建嵌套字典
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
# 转换为多级索引数据框架
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