Python Pandas——设置 MultiIndex 中的级别


要在 MultiIndex 中设置级别,请在 Pandas 中使用 MultiIndex.set_levels() 方法。首先,导入所需库 -

import pandas as pd

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

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

"names" 参数为每个索引级别设置名称。from_arrays() 用于创建 MultiIndex -

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

在 MultiIndex 中设置级别 -

print("\nSet new levels in Multi-index...\n",multiIndex.set_levels([['p', 'q', 'r', 's'], [10, 20, 30, 40]]))

示例

以下是代码 -

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]

# 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 levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)

# set the levels in MultiIndex
print("\nSet new levels in Multi-index...\n",multiIndex.set_levels([['p', 'q', 'r', 's'], [10, 20, 30, 40]]))

输出

这将产生以下输出 -

The Multi-index...
MultiIndex([(1,  'John'),
            (2,   'Tim'),
            (3, 'Jacob'),
            (4, 'Chris')],
            names=['ranks', 'student'])

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

Set new levels in Multi-index...
MultiIndex([('p', 30),
            ('q', 40),
            ('r', 20),
            ('s', 10)],
            names=['ranks', 'student'])

更新于:2021 年 10 月 19 日

796 次查看

开启你的职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.