首页 文章资讯内容详情

Python Pandas - 在 MultiIndex 中获取标签或标签元组的位置

2026-06-03 1 花语

要获取MultiIndex中标签或标签元组的位置,请使用Pandas中的方法。MultiIndex.get_loc()

首先,导入所需的库-

import pandas as pd

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

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

显示多索引-

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

获取位置-

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

示例

以下是代码-

import pandas as pd #MultiIndex是Pandas对象的多级或分层索引对象 multiIndex = pd.MultiIndex.from_arrays([list(pqrrss), list(stuvwx)]) #显示多索引 print("The MultiIndex...\n",multiIndex) #获取MultiIndex中的级别 print("\nThe levels in MultiIndex...\n",multiIndex.levels) #获取位置 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)