首页 文章资讯内容详情

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

2026-06-03 1 花语

要获取MultiIndex中一系列标签的位置,请使用Pandas中的方法。MutiIndex.get_locs()

首先,导入所需的库-

import pandas as pd

MultiIndex是Pandas对象的多级或分层索引对象-

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

显示多索引-

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)]) #显示多索引 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]