Python Pandas - 在 MultiIndex 中获取请求标签/级别的位置和切片索引
要获取MultiIndex中请求的标签/级别的位置和切片索引,请使用get_loc_level()Pandas中的方法。
首先,导入所需的库-
import pandas as pd
MultiIndex是Pandas对象的多级或分层索引对象-
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])显示多索引-
print("The MultiIndex...\n",multiIndex)获取位置和切片索引-
print("\nGet the location and sliced index...\n",multiIndex.get_loc_level('r'))示例
以下是代码-
import pandas as pd
#MultiIndexisamulti-level,orhierarchical,indexobjectforpandasobjects
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])
#displaytheMultiIndex
print("The MultiIndex...\n",multiIndex)
#getthelevelsinMultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)
#Getthelocationandslicedindex
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'))热门推荐
4 简短古诗词祝福语
10 给亲人送祝福语简短
11 立冬来临怎么祝福语简短
12 中秋商务祝福语简短最新
13 舅舅生日祝福语幽默简短
14 出院老师卡片祝福语简短
15 新年拜年祝福语英文简短
16 送同事离职祝福语简短
17 自己的生日简短祝福语
18 长辈新年祝福语大全简短