Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas MultiIndex.reorder_levels() function is used to rearrange levels using input order. It may not drop or duplicate levels. The function take list as an input which contains the desired order of the levels of the MultiIndex.
Syntax: MultiIndex.reorder_levels(order)
Parameters :
order : list containing the order of levelsReturns : A new MultiIndex
Example #1: Use MultiIndex.reorder_levels() function to reorder the levels of the MultiIndex.
# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx) |
Output :
Now let’s reorder the level of the MultiIndex.
# reorder the levels such that# 1st level appears before the 0thmidx.reorder_levels([1, 0]) |
Output :
As we can see in the output, the function has returned a new MultiIndex having the levels set in the passed order.
Example #2: Use MultiIndex.reorder_levels() function to reorder the levels of the MultiIndex.
# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Beagle', 'Sephard', 'Labrador', 'Retriever'], [8, 4, 11, 3], ['A1', 'B1', 'A2', 'C1']]) # Print the MultiIndexprint(midx) |
Output :
Now let’s reorder the levels of the MultiIndex.
# reorder the levelsmidx.reorder_levels([0, 2, 1]) |
Output :
As we can see in the output, the function has returned a new MultiIndex having the levels set in the passed order.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


