Python | Pandas MultiIndex.set_labels ()

Python Methods and Functions

MultiIndex.set_labels() Pandas MultiIndex.set_labels() sets new labels to MultiIndex. By default, a new index is returned.

Syntax: MultiIndex.set_labels (labels, level = None, inplace = False, verify_integrity = True)

Parameters:
labels: new labels to apply
level: level (s) to set (None for all levels )
inplace: if True, mutates in place
verify_integrity: if True, checks that levels and labels are compatible

Returns: new index (of same type and class… etc)

Example # 1: Use MultiIndex.set_labels ( ) to reset MultiIndex labels.

# import pandas as pd

import pandas as pd

  
# Create MultiIndex

midx = pd.MultiIndex. from_tuples ([( 10 , 'Ten' ), ( 10 , 'Twenty ' ),

  ( 20 , 'Ten' ), ( 20 , 'Twenty' )],

names = [ 'Num' , 'Char' ])

  
# Print MultiIndex

print (midx)

Exit :

Now let's reset the MultiIndex tags.

# reset MultiIndex tags

midx.set_labels ([[ 1 , 1 , 0 , 0 ], [ 0 , 1 , 1 , 0 ]])

Output:

As we can see in the output, the MultiIndex tags have been reset.

Example # 2: Use MultiIndex.set_labels () to reset any particular label in MultiIndex only.

# import pandas as pd

import pandas as pd

 
# Create MultiIndex

midx = pd.MultiIndex.from_tuples ([( 10 , ' Ten' ), ( 10 , ' Twenty' ), 

( 20 , 'Ten' ), ( 20 , 'Twenty' )],

names = [ 'Num' , ' Char' ])

 
# Print MultiIndex

print (midx)

Output:

Now let's reset the & # 39; Char & # 39; in MultiIndex.

# reset MultiIndex tags

midx.set_labels ([ 0 , 1 , 1 , 0 ], level = ' Char' )

Output:

As we can see in the output, the “Char” MultiIndex has been reset to the desired value.





Tutorials