Python Pandas - 在 MultiIndex 中獲取標籤序列的位置


要獲取 MultiIndex 中標籤序列的位置,請在 Pandas 中使用 MutiIndex.get_locs() 方法。

首先,匯入所需的庫 −

import pandas as pd

MultiIndex 是 pandas 物件的多級或層次化的索引物件 −

multiIndex = pd.MultiIndex.from_arrays([list('pqrrst'), list('kytssp')])

顯示 MultiIndex −

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

獲取標籤序列的位置 −

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

示例

以下為程式碼 −

import pandas as pd

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

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

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

# Get the location for a sequence of labels
print("\nGet the locations in MultiIndex...\n",multiIndex.get_locs('s'))

輸出

這將產生以下輸出 −

The MultiIndex...
MultiIndex([('p', 'k'),
            ('q', 'y'),
            ('r', 't'),
            ('r', 's'),
            ('s', 's'),
            ('t', 'p')],
           )

The levels in MultiIndex...
   [['p', 'q', 'r', 's', 't'], ['k', 'p', 's', 't', 'y']]

Get the locations in MultiIndex...
   [4]

更新於: 19-Oct-2021

114 瀏覽

助力你的 職業生涯

完成課程以獲得認證

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