Python Pandas - 重新排列多重索引中的级别
要重新排列多重索引中的级别,请在 Pandas 中使用 MultiIndex.reorder_levels() 方法。使用 order 参数设置级别的顺序。
首先,导入所需库 −
import pandas as pd
多重索引是对 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'))
重新排列多重索引的级别。"order" 参数用于设置以某种形式重新排列级别的级别
print("\nReorder levels in MultiIndex...\n",multiIndex.reorder_levels(order=[2, 0, 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'], [50, 30, 40, 70]] # 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=('rank', 'student', 'points')) # display the MultiIndex print("The MultiIndex...\n",multiIndex) # get the levels in MultiIndex print("\nThe levels in MultiIndex...\n",multiIndex.levels) # Reorder levels of MultiIndex # The "order" parameter is used to set the level in a form to reorder levels print("\nReorder levels in MultiIndex...\n",multiIndex.reorder_levels(order=[2, 0, 1]))
输出
这将生成以下输出 −
The MultiIndex... MultiIndex([(2, 'Peter', 50), (4, 'Chris', 30), (3, 'Andy', 40), (1, 'Jacob', 70)], names=['rank', 'student', 'points']) The levels in MultiIndex... [[1, 2, 3, 4], ['Andy', 'Chris', 'Jacob', 'Peter'], [30, 40, 50, 70]] Reorder levels in MultiIndex... MultiIndex([(50, 2, 'Peter'), (30, 4, 'Chris'), (40, 3, 'Andy'), (70, 1, 'Jacob')], names=['points', 'rank', 'student'])
广告