Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python Pandas - 중첩 사전을 다중 인덱스 데이터 프레임으로 변환

<시간/>

먼저 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