Python Pandas - 如何使用每个索引级别的名称来创建一个 MultiIndex


若要创建一个 MultiIndex,请使用 pandas.MultiIndex.from_arrays() 方法。若要设置每个索引级别的名称,请使用 names 参数。

首先,导入所需的库 −

import pandas as pd

MultiIndex 是 pandas 对象的多层次或分层索引对象。创建数组 −

arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]

“names”参数设置每个索引级别的名称。from_arrays() 用于创建一个 Multiindex −

multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))

显示 Multiindex −

print("The Multi-index...\n",multiIndex)

获取 Multiindex 中各层次的名称 −

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)

输出

输出如下 −

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']

更新于: 2021 年 10 月 19 日

527 次浏览

开启 事业

通过完成课程获得认证

开始
广告
© . All rights reserved.