Python Pandas - 獲取此多重索引中的整數級別數


要獲取此多重索引中的整數級別數,請在 Pandas 中使用 MultiIndex.nlevels 屬性。首先,匯入必需的類庫 −

import pandas as pd

MultiIndex 是一個多級或層次 pandas 物件索引物件。建立陣列 −

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

“names”引數設定每個索引級別的名稱。from_arrays() 用於建立一個多索引 −

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

獲取多索引中的整數級別數 −

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

示例

以下為程式碼 −

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 integer number of levels in Multiindex
print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels)

# 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 number of levels in Multi-index...
   2

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

更新於: 2021 年 10 月 19 日

214 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.