
The set_axis() method in pandas let’s you change the rows and columns labels.
syntax –
dataframe.set_axis(labels, axis, inplace)
labels – A list with the indexes
axis – default 0. The axis to update. The value 0 identifies the rows, and 1 identifies the columns.
inplace – Whether to return a new DataFrame instance. Default False.
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]}
df = pd.DataFrame(data)
df

1 . Change the Row Labels –
Let’s say that we want to change the index or row labels. Instead of 0, 1, 2, we want to change then to Jan, Feb, Mar etc.
index_labels = ['Jan','Feb','Mar','Apr','May','June',
'Jul','Aug','Sep','Oct','Nov','Dec']
df = df.set_axis(index_labels, axis='index')
df

2 . Change Column Labels –
Let’s say that we want to change the columns labels. We want all the column labels to in lowercase. We can do this using the set_axis() method in pandas.
col_labels = ['apple','orange','banana','mango']
df = df.set_axis(col_labels, axis='columns')
df
