MultiIndex의 수준을 열로 사용하여 DataFrame을 만들려면 multiIndex.to_frame()을 사용하세요. . 색인 매개변수가 False로 설정됨 반환된 DataFrame의 인덱스 설정을 피하기 위해
먼저 필요한 라이브러리를 가져옵니다 -
import pandas as pd
MultiIndex는 pandas 개체에 대한 다단계 또는 계층적 인덱스 개체입니다. 배열 생성 -
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
"names" 매개변수는 각 인덱스 수준의 이름을 설정합니다. from_arrays()는 MultiIndex를 생성하는 데 사용됩니다 -
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
to_frame()을 사용하여 MultiIndex의 수준을 열로 사용하여 DataFrame을 만듭니다. 반환된 DataFrame의 인덱스를 설정하지 않으려면 "index" 매개변수를 사용하고 "False"로 설정하십시오 -
dataFrame = multiIndex.to_frame(index=False)
예시
다음은 코드입니다 -
import pandas as pd # MultiIndex is a multi-level, or hierarchical, index object for pandas objects # Create arrays arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']] # The "names" parameter sets the names for each of the index levels # The from_arrays() is used to create a MultiIndex multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) # display the MultiIndex print("The Multi-index...\n",multiIndex) # get the levels in MultiIndex print("\nThe levels in Multi-index...\n",multiIndex.levels) # Create a DataFrame with the levels of the MultiIndex as columns using to_frame() # Use the "index" parameter and set it to "False" to avoid setting the index of the returned #DataFrame dataFrame = multiIndex.to_frame(index=False) # Return the DataFrame print("\nThe DataFrame...\n",dataFrame)
출력
이것은 다음과 같은 출력을 생성합니다 -
The Multi-index... MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], names=['ranks', 'student']) The levels in Multi-index... [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']] The DataFrame... ranks student 0 1 John 1 2 Tim 2 3 Jacob 3 4 Chris