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

更新于: 16-9 月-2021

1 千 + 次浏览

开启你的职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.