+

Python | Pandas Index.set_names ()

Index.set_names() Pandas Index.set_names() sets new names in the index. For a given index, it resets the name attribute for that index. By default, the new index is returned. The functions can also be used to reset the multi-index name attribute.

Syntax: Index.set_names (names, level = None, inplace = False)

Parameters:
names: [str or sequence] name (s) to set
level: If the index is a MultiIndex (hierarchical), level (s) to set (None for all levels). Otherwise level must be None
inplace: [bool] if True, mutates in place

Returns: new index (of same type and class… etc) [if inplace, returns None]

Example # 1: Use Index.set_names () to create an anonymous index and setting its name using the name parameter.

# import pandas as pd

import pandas as pd

 
# Create index and set name

pd.Index ([ ` Beagle` , `Pug` , `Labrador` , ` Pug` ,

`Mastiff` , None , `Beagle` ]). set_names ( `Dog_breeds` )

Output:

As we can see in the output, the function has dropped the anonymous index name attribute.

Example # 2: Use Index.set_names () to reset the multi-index name attribute.

# import pandas as pd

import pandas as pd

 
# Create multi-index form tuples

midx = pd.MultiIndex.from_tuples ([( ` Sam` , 21 ), ( `Norah` , 25 ), ( `Jessica` , 32 ),

( `Irwin` , 24 )], names = [ `Name` , ` Age` ] )

 
# Print multi-index
midx

Output:

As we can see in the output, the midx multi-index name attribute is set to "Name" and "Age". Let`s reset these names to "Student_Name" and "Student_Age"

# reset midx name

midx.set_names ([ ` Student_Name` , `Student_Age ` ])

Output:

As we can see in the output, the function has dropped the attribute name multi-index midx .

Get Solution for free from DataCamp guru