Python Pandas - 获取 MultiIndex 中标签序列的位置

pythonserver side programmingprogramming更新于 2026/1/21 0:44:17

要获取 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 是 pandas 对象的多级或分层索引对象
multiIndex = pd.MultiIndex.from_arrays([list('pqrrst'), list('kytssp')])

# 显示 MultiIndex
print("The MultiIndex...\n",multiIndex)

# 获取 MultiIndex 中的级别
print("\nThe levels in MultiIndex...\n",multiIndex.levels)

# 获取标签序列的位置
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]

相关文章


有用资源