+

Python | Pandas Series.rename_axis ()

Series.rename_axis() Pandas Series.rename_axis() is used to set the axis name for the index, or columns.

Syntax: Series.rename_axis (mapper = None, index = None, columns = None, axis = None, copy = True, inplace = False)

Parameter:
mapper: Value to set the axis name attribute.
index, columns: A scalar, list-like, dict-like or functions transformations to apply to that axis` values.
axis: The axis to rename.
copy: Also copy underlying data.
inplace: Modifies the object directly, instead of creating a new Series or DataFrame.

Returns: Series, DataFrame, or None

Example # 1: Use Series.rename_axis () to rename the axis of this Series object.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 10 , 25 , 3 , 11 , 24 , 6 ])

 
# Create index

index_ = [ `Coca Cola` , `Sprite` , `Coke` , ` Fanta` , `Dew` , ` ThumbsUp` ]

 
# set index

sr.index = index_

 
# Print series

print (sr)

Output:

We will now use Series. rename_axis () to rename the axis of the given object series object.

# rename axis

result = sr.rename_axis ( `Beverages` )

 
# Print result

print (result)

Output:


As we can see in the output, Series.rename_axis () successfully renamed the axis of this series object.

Example # 2: Use Series.rename_axis () to rename the MultiIndex axis of this Series object.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ `New York` , ` Chicago` , `Toronto` , `Lisbon` , ` Rio` ])

  
# Create MultiIndex

index_ = pd.MultiIndex.from_product ([[ `Names` ], [ ` City 1` , `City 2 ` , ` City 3` , `City 4` , ` City 5` ]],

names = [ `Level 1` , ` Level 2` ])

 
# set index

sr.index = index_

 
# Print series

print (sr)  

Output:

We will now use Series.rename_axis () to rename the axis of this series object .

# rename both axis levels
# this series object

result = sr.rename_axis ([ `First_level` , ` Second_level` ] )

 
# Print result

print (result)

Exit d:

As we can see in the output, Series.rename_axis () has successfully renamed both axis levels of this series object.

Get Solution for free from DataCamp guru