Python Pandas - 获取 MultiIndex 中的代码(每个标签的位置)
要获取MultiIndex中的代码(每个标签的位置),请使用Pandas中的MultiIndex.codes属性。首先,导入所需的库-
import pandas as pd
MultiIndex是Pandas对象的多级或分层索引对象。创建数组-
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
“名称”参数设置每个索引级别的名称:from_arrays()用于创建多索引-
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))获取Multiindex中每个标签的位置-
print("\nThe location of each label in Multi-index...\n",multiIndex.codes)示例
以下是代码-
import pandas as pd
#MultiIndexisamulti-level,orhierarchical,indexobjectforpandasobjects
#Createarrays
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
# The "names" parameter sets the names for each of the index levels
#Thefrom_arrays()isusedtocreateaMultiindex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
#displaytheMultiindex
print("The Multi-index...\n",multiIndex)
#getthelevelsinMultiindex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
#getthelocationofeachlabelinMultiindex
print("\nThe location of each label in Multi-index...\n",multiIndex.codes)输出结果这将产生以下输出-
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris'),
(5, 'Keiron')],
names=['ranks', 'student'])
The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
The location of each label in Multi-index...
[[0, 1, 2, 3, 4], [2, 4, 1, 0, 3]]