Python Pandas - 在 MultiIndex 中获取标签序列的位置
要获取 MultiIndex 中标签序列的位置,请在 Pandas 中使用 MutiIndex.get_locs() 方法。
首先,导入所需的库 −
import pandas as pd
MultiIndex 是 pandas 对象的多级或层次化的索引对象 −
multiIndex = pd.MultiIndex.from_arrays([list('pqrrst'), list('kytssp')])
显示 MultiIndex −
print("The MultiIndex...\n",multiIndex)
获取标签序列的位置 −
print("\nGet the locations in MultiIndex...\n",multiIndex.get_locs('s'))
示例
以下为代码 −
import pandas as pd # MultiIndex is a multi-level, or hierarchical, index object for pandas objects multiIndex = pd.MultiIndex.from_arrays([list('pqrrst'), list('kytssp')]) # display the MultiIndex print("The MultiIndex...\n",multiIndex) # get the levels in MultiIndex print("\nThe levels in MultiIndex...\n",multiIndex.levels) # Get the location for a sequence of labels 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]
广告