pandas.MultiIndex.reorder_levels#
- MultiIndex.reorder_levels(order)[source]#
Rearrange levels using input order. May not drop or duplicate levels.
reorder_levels is useful when you need to change the order of levels in a MultiIndex, such as when reordering levels for hierarchical indexing. It maintains the integrity of the MultiIndex, ensuring that all existing levels are present and no levels are duplicated. This method is helpful for aligning the index structure with other data structures or for optimizing the order for specific data operations.
- Parameters:
- orderlist of int or list of str
List representing new level order. Reference level by number (position) or by key (label).
- Returns:
- MultiIndex
A new MultiIndex with levels rearranged according to the specified order.
See also
MultiIndex.swaplevel
Swap two levels of the MultiIndex.
MultiIndex.set_names
Set names for the MultiIndex levels.
DataFrame.reorder_levels
Reorder levels in a DataFrame with a MultiIndex.
Examples
>>> mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]], names=["x", "y"]) >>> mi MultiIndex([(1, 3), (2, 4)], names=['x', 'y'])
>>> mi.reorder_levels(order=[1, 0]) MultiIndex([(3, 1), (4, 2)], names=['y', 'x'])
>>> mi.reorder_levels(order=["y", "x"]) MultiIndex([(3, 1), (4, 2)], names=['y', 'x'])