Python Pandas - 獲取 MultiIndex 的級別


若要獲取 MultiIndex 中的級別,請使用 Pandas 中的 MultiIndex.levels 屬性。首先,匯入所需的庫:

import pandas as pd

MultiIndex 是 pandas 物件的多層次(或分層)索引物件。建立陣列:

arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

"names" 引數為索引的每個級別設定名稱。from_arrays() 用於建立 Multiindex:

multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

在 Multiindex 中獲取級別:

print("\nThe levels in Multi-index...\n",multiIndex.levels)

示例

以下為該程式碼:

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

# The "names" parameter sets the names for each of the index levels
# The from_arrays() uis 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)

輸出

這將產生以下輸出:

The Multi-index...
MultiIndex([(1, 'John'),
            (2, 'Tim'),
            (3, 'Jacob'),
            (4, 'Chris'),
            (5, 'Keiron')],
            names=['ranks', 'student'])

The levels in Multi-index...
   [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]

更新時間:19-Oct-2021

2K+ 瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.