Python Pandas - 如何按特定级别降序排序多级索引
要创建多级索引,请使用 **from_arrays()** 方法。但是,要按特定级别对多级索引进行排序,请在 Pandas 中使用 **multiIndex.sortlevel()** 方法。将级别设置为参数。要按降序排序,请使用 **ascending** 参数并将其设置为 **False**。
首先,导入所需的库 -
import pandas as pd
多级索引是 Pandas 对象的多级或分层索引对象。创建数组 -
arrays = [[2, 4, 3, 1], ['Peter', 'Chris', 'Andy', 'Jacob']]
"names" 参数为每个索引级别设置名称。from_arrays() 用于创建多级索引 -
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
排序多级索引。要排序的特定级别设置为参数,即此处为级别 1。我们使用值为“False”的“ascending”顺序以降序排序 -
print("\nSort MultiIndex at the requested level in descending order...\n",multiIndex.sortlevel(1, ascending=False))
示例
以下是代码 -
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 # We have sort in descending order using the "ascending" order with value "False" print("\nSort MultiIndex at the requested level in descending order...\n",multiIndex.sortlevel(1, ascending=False))
输出
这将产生以下输出 -
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 in descending order... (MultiIndex([(2, 'Peter'), (1, 'Jacob'), (4, 'Chris'), (3, 'Andy')], names=['ranks', 'student']), array([0, 3, 1, 2], dtype=int64))
广告