Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Pandas – 중첩 딕셔너리를 멀티인덱스 데이터프레임으로 변환하는 방법

개요

Pandas에서 중첩 딕셔너리(nested dictionary)멀티인덱스(Multi-index) 데이터프레임으로 변환하려면, 딕셔너리의 키를 튜플 형태로 구성한 뒤 pd.DataFrame()에 전달하면 됩니다. 튜플 형태의 키는 Pandas가 자동으로 계층형 컬럼(멀티인덱스)으로 인식합니다.

먼저 중첩 딕셔너리를 생성해 보겠습니다.

dictNested = {
   'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'], 'Country': ['India', 'Australia', 'England']},
   'Football': {'Boards': ['TFA', 'TCSA', 'GFA'], 'Country': ['England', 'Canada', 'Germany']}
}

이제 변환 결과를 담을 빈 딕셔너리를 생성합니다.

new_dict = {}

반복문을 사용해 외부 키(outer key)와 내부 키(inner key)를 튜플로 묶어 새 딕셔너리에 값을 할당합니다. 이 과정에서 중첩된 구조가 평탄화(flatten)됩니다.

for outerKey, innerDict in dictNested.items():
   for innerKey, values in innerDict.items():
      new_dict[(outerKey, innerKey)] = values

마지막으로 pd.DataFrame()을 호출해 멀티인덱스 데이터프레임으로 변환합니다.

pd.DataFrame(new_dict)

전체 예제 코드

다음은 위 과정을 모두 포함한 전체 코드입니다.

import pandas as pd

# 중첩 딕셔너리 생성
dictNested = {'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'], 'Country': ['India', 'Australia', 'England']},
              'Football': {'Boards': ['TFA', 'TCSA', 'GFA'], 'Country': ['England', 'Canada', 'Germany']}}

print("\n중첩 딕셔너리...\n", dictNested)

new_dict = {}
for outerKey, innerDict in dictNested.items():
    for innerKey, values in innerDict.items():
        new_dict[(outerKey, innerKey)] = values

# 멀티인덱스 데이터프레임으로 변환
print("\n멀티인덱스 데이터프레임...\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

핵심 포인트 정리

  • 딕셔너리의 키를 (외부키, 내부키) 형태의 튜플로 만들면 Pandas가 이를 자동으로 멀티인덱스 컬럼으로 인식합니다.
  • dict.items()를 이중 반복문으로 순회하여 중첩 구조를 하나의 딕셔너리로 평탄화합니다.
  • 변환된 데이터프레임은 df['Cricket']['Boards']처럼 계층적으로 접근할 수 있어 복잡한 데이터를 체계적으로 다루기에 적합합니다.