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 千 + 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始學習
廣告