MultiIndex를 레벨 값이 포함된 튜플 인덱스로 변환하려면 MultiIndex.to_flat_index()를 사용하세요. 방법.
먼저 필요한 라이브러리를 가져옵니다 -
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')) MultiIndex 변환 -
print("\nConverting a MultiIndex to an Index of Tuples containing the level values...\n",multiIndex.to_flat_index()) 예시
다음은 코드입니다 -
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)
# Convert the MultiIndex
print("\nConverting a MultiIndex to an Index of Tuples containing the level values...\n",multiIndex.to_flat_index()) 출력
이것은 다음과 같은 출력을 생성합니다 -
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']]
Converting a MultiIndex to an Index of Tuples containing the level values...
Index([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], dtype='object')