Python Pandas - 获取 MultiIndex 中请求标签/级别的位置和切片索引
pythonserver side programmingprogramming更新于 2026/1/21 1:48:17
要获取 MultiIndex 中请求标签/级别的位置和切片索引,请使用 Pandas 中的 get_loc_level() 方法。
首先,导入所需的库 −
import pandas as pd
MultiIndex 是 pandas 对象的多级或分层索引对象 −
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])
显示 MultiIndex −
print("The MultiIndex...\n",multiIndex)
获取位置和切片索引 −
print("\nGet the location and splitd index...\n",multiIndex.get_loc_level('r'))
示例
以下是代码 −
import pandas as pd
# MultiIndex 是 pandas 的多级或分层索引对象对象
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])
# 显示 MultiIndex
print("The MultiIndex...\n",multiIndex)
# 获取 MultiIndex 中的级别
print("\nThe levels in MultiIndex...\n",multiIndex.levels)
# 获取位置和切片索引
print("\nGet the location and sliced index...\n",multiIndex.get_loc_level('r'))
输出
这将产生以下输出 −
The MultiIndex...
MultiIndex([('p', 's'),
('q', 't'),
('r', 'r'),
('r', 'v'),
('s', 'w'),
('s', 'x')],
names=['One', 'Two'])
The levels in MultiIndex...
[['p', 'q', 'r', 's'], ['r', 's', 't', 'v', 'w', 'x']]
Get the location and sliced index...
(slice(2, 4, None), Index(['r', 'v'], dtype='object', name='Two'))
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

