Python Pandas - 多索引的交换级别
要交换MultiIndex的级别,请使用swaplevel()Pandas中的方法。要交换的级别应作为参数提及。
首先,导入所需的库-
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的级别swaplevel()。第一个参数是要交换的第一级索引。第二个参数是要交换的第二级索引-
print("\nSwap levels in MultiIndex...\n",multiIndex.swaplevel(0,2))
示例
以下是代码-
import pandas as pd #MultiIndexisamulti-level,orhierarchical,indexobjectforpandasobjects #Createarrays 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 #Thefrom_arrays()isusedtocreateaMultiIndex multiIndex = pd.MultiIndex.from_arrays(arrays, names=('rank', 'student', 'points')) #displaytheMultiIndex print("The MultiIndex...\n",multiIndex) #getthelevelsinMultiIndex print("\nThe levels in MultiIndex...\n",multiIndex.levels) #swaplevelsofMultiIndexusingswaplevel() #The1stparameteristhefirstlevelofindextobeswapped #The2ndparameteristhesecondlevelofindextobeswapped print("\nSwap levels in MultiIndex...\n",multiIndex.swaplevel(0,2))输出结果
这将产生以下输出-
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]] Swap levels in MultiIndex... MultiIndex([(50, 'Peter', 2), (30, 'Chris', 4), (40, 'Andy', 3), (70, 'Jacob', 1)], names=['points', 'student', 'rank'])