pandas.MultiIndex.swaplevel#
- MultiIndex.swaplevel(i=-2, j=-1)[source]#
Swap level i with level j.
Calling this method does not change the ordering of the values.
Default is to swap the last two levels of the MultiIndex.
- Parameters:
- iint, str, default -2
First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed. If i is a negative int, the first level is indexed relative to the end of the MultiIndex.
- jint, str, default -1
Second level of index to be swapped. Can pass level name as string. Type of parameters can be mixed. If j is a negative int, the second level is indexed relative to the end of the MultiIndex.
- Returns:
- MultiIndex
A new MultiIndex.
See also
Series.swaplevelSwap levels i and j in a MultiIndex.
DataFrame.swaplevelSwap levels i and j in a MultiIndex on a particular axis.
Examples
>>> mi = pd.MultiIndex( ... levels=[["a", "b"], ["bb", "aa"], ["aaa", "bbb"]], ... codes=[[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 1, 0]], ... ) >>> mi MultiIndex([('a', 'bb', 'bbb'), ('a', 'aa', 'aaa'), ('b', 'bb', 'bbb'), ('b', 'aa', 'aaa')], ) >>> mi.swaplevel() MultiIndex([('a', 'bbb', 'bb'), ('a', 'aaa', 'aa'), ('b', 'bbb', 'bb'), ('b', 'aaa', 'aa')], ) >>> mi.swaplevel(0) MultiIndex([('bbb', 'bb', 'a'), ('aaa', 'aa', 'a'), ('bbb', 'bb', 'b'), ('aaa', 'aa', 'b')], ) >>> mi.swaplevel(0, 1) MultiIndex([('bb', 'a', 'bbb'), ('aa', 'a', 'aaa'), ('bb', 'b', 'bbb'), ('aa', 'b', 'aaa')], )