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() uis 用于创建 Multiindex −
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)
广告