Python Pandas - 在 MultiIndex 中获取标签或标签元组的位置
要获取 MultiIndex 中标签或标签元组的位置,请使用 Pandas 中的MultiIndex.get_loc() 方法。
首先,导入所需的库 −
import pandas as pd
MultiIndex 是 Pandas 对象的多级或分层索引对象 −
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('stuvwx')])
显示 MultiIndex −
print("The MultiIndex...\n",multiIndex)获取位置 −
print("\nGet the locations in MultiIndex...\n",multiIndex.get_loc('s'))
示例
以下为代码 −
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('stuvwx')])
# display the MultiIndex
print("The MultiIndex...\n",multiIndex)
# get the levels in MultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)
# Get the location
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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP