Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas – Chuyển Nested Dictionary thành MultiIndex DataFrame

Giới thiệu

Để chuyển đổi một nested dictionary (dictionary lồng nhau) thành DataFrame đa chỉ số (MultiIndex columns), ta có thể flatten dictionary thành dict với key là tuple (outer_key, inner_key), sau đó tạo DataFrame.

Ví dụ minh họa

import pandas as pd

# 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

# Chuyển thành MultiIndex DataFrame
print("\nMulti-index DataFrame...\n", pd.DataFrame(new_dict))

Kết quả đầu ra

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

Giải thích: Cột thành MultiIndex với level 0: Cricket/Football, level 1: Boards/Country.