ขั้นแรก ให้เราสร้าง Nested Dictionary -
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
แปลงเป็น DataFrame แบบหลายดัชนี -
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