Sunday, November 17, 2024
Google search engine
HomeLanguagesPython | Pandas Index.set_names()

Python | Pandas Index.set_names()

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 Index.set_names() function set new names on index. For the given Index it resets the name attribute for that Index. It defaults to returning new index. The functions can also be used to reset the name attribute of the multi-index.

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() function create an anonymous Index and set its name using the name parameter.




# importing pandas as pd
import pandas as pd
  
# Creating the index and setting the 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 reset the name attribute of the anonymous Index.
 
Example #2: Use Index.set_names() function to reset the name attribute of the multi-index.




# importing pandas as pd
import pandas as pd
  
# Creating the multi-index form tuples
midx = pd.MultiIndex.from_tuples([('Sam', 21), ('Norah', 25), ('Jessica', 32),
                                       ('Irwin', 24)], names =['Name', 'Age'])
  
# Print the Multi-Index
midx


Output :

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




# to reset the name of the midx
midx.set_names(['Student_Name', 'Student_Age'])


Output :

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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments