Python Pandas - 获取多重索引中的层级名称


要在多重索引中获取层级名称,在 Pandas 中使用 MultiIndex.names 属性。首先,导入所需库 −

import pandas as pd

多重索引是 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 names of levels in Multi-index...\n",multiIndex.names)

示例

以下是代码 −

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() is 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 names of levels in Multiindex
print("\nThe names of levels in Multi-index...\n",multiIndex.names)

# 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 names of levels in Multi-index...
['ranks', 'student']

The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]

更新于: 19-10-2021

2K+ 浏览

助力你的 职业

完成该课程以获得认证

开始
广告