要从 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 # MultiIndex is a multi-level, or hierarchical, index object for pandas objects # Create arrays arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']] # The "names" parameter sets the names for each of the index levels # The from_arrays() uis used to create a Multiindex multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) # display the Multiindex print("The Multi-index...\n",multiIndex) # get the integer number of levels in Multiindex print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels) # get the levels in Multiindex print("\nThe levels in Multi-index...\n",multiIndex.levels) # get a tuple with the length of each level 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)