Python Pandas - 如何对多重索引进行排序
要创建多索引,可以使用 from_arrays() 方法。但是,要对多索引进行排序,请在 Pandas 中使用 multiIndex.sortlevel() 方法。
首先,导入必需的库 −
import pandas as pd
多索引是 panda 对象的多级或层次索引对象。创建数组 −
arrays = [[2, 4, 3, 1], ['John', 'Tim', 'Jacob', 'Chris']]
"names" 参数设置每个索引级别的名称。from_arrays() 用于创建 MultiInde −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
对多索引排序。默认情况下,在级别 0 进行排序 −
print("\nSort MultiIndex...\n",multiIndex.sortlevel())
示例
以下是代码 −
import pandas as pd # MultiIndex is a multi-level, or hierarchical, index object for pandas objects # Create arrays arrays = [[2, 4, 3, 1], ['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) # Sort MultiIndex # The default sorts at level 0 print("\nSort MultiIndex...\n",multiIndex.sortlevel())
输出
这将生成以下输出 −
The Multi-index... MultiIndex([(2, 'John'), (4, 'Tim'), (3, 'Jacob'), (1, 'Chris')], names=['ranks', 'student']) The levels in Multi-index... [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']] Sort MultiIndex... (MultiIndex([(1, 'Chris'), (2, 'John'), (3, 'Jacob'), (4, 'Tim')], names=['ranks', 'student']), array([3, 0, 2, 1], dtype=int64))
广告