要返回使用级别名称删除多个级别的 MultiIndex,请使用该方法并将要删除的多个级别(级别名称)设置为参数。MultiIndex.droplevel()
首先,导入所需的库 -
import pandas as pd
MultiIndex 是 Pandas 对象的多级或分层索引对象。创建数组 -
arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]]
“names”参数设置每个索引级别的名称。将from_arrays()被用来创建一个多指标-
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points'))
从 MultiIndex 删除特定级别。要删除的级别设置为参数中的级别名称,即级别名称“学生”和“等级”被删除 -
print("\nMulti-index after dropping two levels...\n",multiIndex.droplevel(['rank', 'student']))
以下是代码 -
import pandas as pd # MultiIndex 是 Pandas 对象的多级或分层索引对象 # 创建数组 arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob'], [50, 30, 40, 70]] # The "names" parameter sets the names for each of the index levels # from_arrays() 用于创建 MultiIndex multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points')) # 显示多索引 print("The Multi-index...\n",multiIndex) # 获取 MultiIndex 中的级别 print("\nThe levels in Multi-index...\n",multiIndex.levels) # 从 MultiIndex 删除特定级别 # 要删除的级别设置为参数 ie 中的级别名称 # level name 'student' and 'rank' gets dropped print("\nMulti-index after dropping two levels...\n",multiIndex.droplevel(['rank', 'student']))输出结果
这将产生以下输出 -
The Multi-index... MultiIndex([(2, 'Peter', 50), (4, 'Chris', 30), (3, 'Andy', 40), (1, 'Jacob', 70)], names=['rank', 'student', 'points']) The levels in Multi-index... [[1, 2, 3, 4], ['Andy', 'Chris', 'Jacob', 'Peter'], [30, 40, 50, 70]] Multi-index after dropping two levels... Int64Index([50, 30, 40, 70], dtype='int64', name='points')