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
#创建嵌套字典
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