Python Pandas - 获取此多重索引中的整数级别数
要获取此多重索引中的整数级别数,请在 Pandas 中使用 MultiIndex.nlevels 属性。首先,导入必需的类库 −
import pandas as pd
MultiIndex 是一个多级或层次 pandas 对象索引对象。创建数组 −
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
“names”参数设置每个索引级别的名称。from_arrays() 用于创建一个多索引 −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
获取多索引中的整数级别数 −
print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels)
示例
以下为代码 −
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)
输出
将产生以下输出 −
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']]
广告