Python | Pandas MultiIndex.swaplevel ()



MultiIndex.swaplevel() Pandas MultiIndex.swaplevel() is used to switch MultiIndex levels. Swap level i with level j. Calling this method does not change the order of the values.

Syntax: MultiIndex.swaplevel (i = -2, j = -1)

Parameters:
i: First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.
j: Second level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.

Returns: A new MultiIndex

Example # 1: Use MultiIndex.swaplevel () to change the 0th level to the 1st level of MultiIndex.

# import pandas as pd

import pandas as pd

 
# Create MultiIndex

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

  `Anthropology` , ` Science` < code class = "plain">], 

[ 88 , 84 , 98 , 95 ]])

 
# Print MultiIndex

print (midx)

Output:

Now let`s swap the 0th level with the 1st level of MultiIndex.

# change levels

midx.swaplevel ( 0 , 1 )

Output:

As we can see in the output, the function changed the 0th level to the 1st level of MultiIndex.

Example # 2: Use MultiIndex.swaplevel () to change the 0th level to the 1st level of MultiIndex.

# import pandas as pd

import pandas as pd

  
# 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 0th level to the 2nd level of MultiIndex.

# change levels

midx.swaplevel ( 0 , 2 )

Output:

As we can see in the output, the function changed the 0th level to the 2nd level of MultiIndex.