Python Pandas - 从 MultiIndex 获取每个级别长度的元组
要从MultiIndex获取具有每个级别长度的元组,请使用Pandas中的MultiIndex.levshape属性。
首先,导入所需的库-
import pandas as pd
MultiIndex是Pandas对象的多级或分层索引对象。创建数组-
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
“names”参数设置每个索引级别的名称。from_arrays()用于创建Multiindex的uis-
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
获取每个级别长度的元组-
print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape)
示例
以下是代码-
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()uisusedtocreateaMultiindex multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) #displaytheMultiindex print("The Multi-index...\n",multiIndex) #gettheintegernumberoflevelsinMultiindex print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels) #getthelevelsinMultiindex print("\nThe levels in Multi-index...\n",multiIndex.levels) #getatuplewiththelengthofeachlevel print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape)输出结果
这将产生以下输出-
The Multi-index... MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris'), (5, 'Keiron')], names=['ranks', 'student']) The number of levels in Multi-index... 2 The levels in Multi-index... [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']] The tuple with the length of each level in a Multi-index... (5, 5)