
The rename_axis() method in pandas let’s us set the name of the axis for the index or columns.
Syntax –
dataframe.rename_axis(mapper, index, columns, axis, copy, inplace)
mapper – A string or list with the new name of the axis
index – A string, list, or a dictionary with the new name of the row axis
columns – A string, list, or a dictionary with the new name of the column axis
axis – The axis to rename.
copy – Also copy underlying data.
inplace – Modifies the object directly, instead of creating a new Series or DataFrame.
Examples –
Let’s create a dataframe to work with.
import pandas as pd
data = {'Apple':[89, 89, 90, 110, 125, 84, 131, 123, 123, 140, 145, 145],
'Orange': [46, 46, 50, 65, 63, 48, 110, 120, 60, 42, 47, 62],
'Banana': [26, 30, 30, 25, 38, 22, 22, 36, 20, 27, 23, 34 ],
'Mango': [80, 80, 90, 125, 130, 150, 140, 140, 135, 135, 80, 90]}
index = ['Jan','Feb','Mar','Apr','May','June','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame(data, index=index)
df

1 . set the name of the axis for the index –
To set the name of the axis for the index, we can use the rename_axis() method. As the index of our dataframe contains name of months, let’s set it’s name to Months.
df.rename_axis("Months", inplace=True)
df

2 . Set the name of the axis for the columns –
To set the name of the axis for the columns, we need to set the axis parameter to axis=1 or columns. Since the columns in our dataframe represents fruits, let’s name it to Fruits.
df.rename_axis("Fruits", axis='columns', inplace=True)
df
