Python Pandas - 使用级别名称删除请求的级别后返回 MultiIndex


要使用级别名称删除请求的级别后返回 MultiIndex,请使用 **MultiIndex.droplevel()** 方法并将要删除的级别(级别名称)设置为参数。

首先,导入所需的库 -

import pandas as pd

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

arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob']]

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

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

从 MultiIndex 中删除特定级别。要删除的级别在参数中设置为级别名称,即

# 删除级别名称“student” -

print("\nMulti-index after dropping a level...\n",multiIndex.droplevel('student'))

示例

以下是代码 -

import pandas as pd

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

# 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)

# Drop a specific level from MultiIndex
# The level to be dropped is set as the level name in parameter i.e.
# level name 'student' gets dropped
print("\nMulti-index after dropping a level...\n",multiIndex.droplevel('student'))

输出

这将产生以下输出 -

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

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

Multi-index after dropping a level...
   Int64Index([2, 4, 3, 1], dtype='int64', name='ranks')

更新于: 2021-10-19

112 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告