Python Pandas - 在 MultiIndex 中獲取標籤或標籤元組的位置


要獲取 MultiIndex 中標籤或標籤元組的位置,請使用 Pandas 中的MultiIndex.get_loc() 方法。

首先,匯入所需的庫 −

import pandas as pd

MultiIndex 是 Pandas 物件的多級或分層索引物件 −

multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('stuvwx')])

顯示 MultiIndex −

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

獲取位置 −

print("\nGet the locations in MultiIndex...\n",multiIndex.get_loc('s'))

示例

以下為程式碼 −

import pandas as pd

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

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

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

# Get the location
print("\nGet the locations in MultiIndex...\n",multiIndex.get_loc('s'))

輸出

將生成以下輸出 −

The MultiIndex...
MultiIndex([('p', 's'),
            ('q', 't'),
            ('r', 'u'),
            ('r', 'v'),
            ('s', 'w'),
            ('s', 'x')],
           )

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

Get the locations in MultiIndex...
   slice(4, 6, None)

更新日期:19-10-2021

瀏覽量:147

開啟你的 職業生涯

完成課程並獲得認證

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