Python Pandas - 利用 MultiIndex 中級別的整數位置返回標籤值向量


若要利用 MultiIndex 中級別的整數位置返回標籤值向量,請在 Pandas 中使用 MultiIndex.get_level_values() 方法。設定級別作為引數。

首先,匯入必需的庫 -

import pandas as pd

MultiIndex 是 pandas 物件的多級或分層索引物件 -

multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])

顯示 MultiIndex -

print("The MultiIndex...\n",multiIndex)

在級別 0 獲取級別值 -

print("\nLevel values at level 0...\n",multiIndex.get_level_values(0))

示例

以下是程式碼 -

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])

# display the MultiIndex
print("The MultiIndex...\n",multiIndex)

# get the levels in MultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)

# get level values at level 0
print("\nLevel values at level 0...\n",multiIndex.get_level_values(0))

輸出

這將產生以下輸出 -

The MultiIndex...
MultiIndex([('p', 's'),
            ('q', 't'),
            ('r', 'r'),
            ('r', 'v'),
            ('s', 'w'),
            ('s', 'x')],
            names=['One', 'Two'])

The levels in MultiIndex...
   [['p', 'q', 'r', 's'], ['r', 's', 't', 'v', 'w', 'x']]

Level values at level 0...
   Index(['p', 'q', 'r', 'r', 's', 's'], dtype='object', name='One')

更新日期:2021-10-19

126 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.