Đầu tiên, hãy tạo Từ điển lồng nhau -
dictNested = {'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'],'Country': ['India', 'Australia', 'England']},'Football': {'Boards': ['TFA', 'TCSA', 'GFA'],'Country': ['England', 'Canada', 'Germany']
}} Bây giờ, hãy tạo Từ điển trống -
new_dict = {} Bây giờ, vòng lặp để gán giá trị -
for outerKey, innerDict in dictNested.items():
for innerKey, values in innerDict.items():
new_dict[(outerKey, innerKey)] = values
Chuyển đổi sang DataFrame đa chỉ mục -
pd.DataFrame(new_dict)
Ví dụ
Sau đây là mã -
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) Đầu ra
Điều này sẽ tạo ra kết quả sau -
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