Python | Pandas MultiIndex.reorder_levels ()

MultiIndex.reorder_levels() Pandas MultiIndex.reorder_levels() is used to reorder levels using input order … It cannot drop or duplicate levels. The function takes a list of inputs that contains the desired order of MultiIndex levels.

Syntax: MultiIndex.reorder_levels (order)

Parameters:
order: list containing the order of levels

Returns: A new MultiIndex

Example # 1: Use MultiIndex.reorder_levels () to reorder MultiIndex levels.

# import pandas as pd

import pandas as pd

 
# Create MultiIndex

midx = pd.MultiIndex.from_arrays ([[ `Networking`  , `Cryptography`

  `Anthropology` , ` Science` ], 

[ 88 , 84 , 98 , 95 ]])

 
# Print MultiIndex

print (midx)

Output:

Now let`s change the MultiIndex level.

# reorder levels so that
# 1st level appears before 0th

midx.reorder_levels ([ 1 , 0 ])

Output:

As we can see in the output, the function returned a new MultiIndex with levels set in the order passed.

Example # 2: Use MultiIndex.reorder_levels () to reorder MultiIndex levels.

# import pandas as pd

import pandas as pd < / code>

 
# Create MultiIndex

midx = pd.MultiIndex.from_arrays ([[ ` Beagle` , `Sephard` , `Labrador` , ` Retriever` ], 

  [ 8 , 4 , 11 , 3 ], [ `A1` , ` B1` , `A2` , `C1` ]])

  
# Print MultiIndex

print (midx)

Output:

Now let`s change the order of the MultiIndex levels.

# change the order of levels

midx.reorder_levels ([ 0 , 2 , 1 ])

Output:

Like As we see in the output, the function returned a new MultiIndex with the levels set in the passed order.