要创建 MultiIndex,请使用from_arrays()方法。但是,要在特定级别对 MultiIndex 进行排序,请使用Pandas 中的方法。将级别设置为参数。multiIndex.sortlevel()
首先,导入所需的库 -
import pandas as pd
MultiIndex 是 Pandas 对象的多级或分层索引对象。创建数组:
arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob']]
“names”参数设置每个索引级别的名称。将from_arrays()被用来创建一个多指标-
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
排序多索引。要排序的特定级别设置为参数,即此处的级别 1 -
print("\nSort MultiIndex at the requested level...\n",multiIndex.sortlevel(1))
以下是代码 -
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) # Sort MultiIndex # The specific level to sort is set as a parameter i.e. level 1 here print("\nSort MultiIndex at the requested level...\n",multiIndex.sortlevel(1))输出结果
这将产生以下输出 -
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']] Sort MultiIndex at the requested level... (MultiIndex([(3, 'Andy'), (4, 'Chris'), (1, 'Jacob'), (2, 'Peter')], names=['ranks', 'student']), array([2, 1, 3, 0], dtype=int64))