要返回 MultiIndex 中请求级别的标签值向量,请使用该方法。将级别名称设置为参数。multiIndex.get_level_values()
首先,导入所需的库 -
import pandas as pd
MultiIndex 是 Pandas 对象的多级或分层索引对象 -
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])
显示多索引 -
print("The MultiIndex...\n",multiIndex)
获取 MultiIndex 中的级别 -
print("\nThe levels in MultiIndex...\n",multiIndex.levels)
获取级别 0 的级别值 -
print("\nLevel values...\n",multiIndex.get_level_values(0))
以下是代码 -
import pandas as pd # MultiIndex is a multi-level, or hierarchical, index object for pandas objects multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two']) # display the MultiIndex print("The MultiIndex...\n",multiIndex) # get the levels in MultiIndex print("\nThe levels in MultiIndex...\n",multiIndex.levels) # get level values at level 0 print("\nLevel values...\n",multiIndex.get_level_values(0)) # get level values with level name "Two" print("\nLevel values...\n",multiIndex.get_level_values("Two"))输出结果
这将产生以下输出 -
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']] Level values... Index(['p', 'q', 'r', 'r', 's', 's'], dtype='object', name='One') Level values... Index(['s', 't', 'r', 'v', 'w', 'x'], dtype='object', name='Two')