Rename DataFrame columns/index names

Renaming DataFrame columns and index names is a common operation that allows data professionals to customize the DataFrame's structure to their requirements, improve readability, and provide more informative labels. Pandas provides several methods to achieve this, including rename(), columns, index, and assigning new values directly. You can simply rename DataFrame column names using DataFrame.rename() .

DataFrame.rename({'oldName1': 'newName1', 'oldName2': 'newName2'}, axis=1)

Lets create a DataFrame..

import pandas as pd import numpy as np df = pd.DataFrame() df['A'] = [12,13,12] df['B'] = [45, 40, 48] df
A B 0 12 45 1 13 40 2 12 48

Rename DataFrame column using DataFrame.rename()

df.rename({'A': 'Age','B':'Marks'}, axis=1, inplace=True) df

rename dataframe column
Age Marks 0 12 45 1 13 40 2 12 48

Rename DataFrame index using DataFrame.rename()

df.rename({0: 'One',1:'Two', 2:'Three' }, axis=0, inplace=True) df
A B One 12 45 Two 13 40 Three 12 48

Reassign DataFrame column/index names using set_axis()

df.set_axis(['Age', 'Marks'], axis=1, inplace=True) df
Age Marks 0 12 45 1 13 40 2 12 48

Changing DataFrame Index label using DataFrame.set_axis()

df.set_axis(['Age', 'Marks', 'Grade'], axis=0, inplace=True) df

rename dataframe index labels
A B Age 12 45 Marks 13 40 Grade 12 48

Conclusion

Renaming DataFrame columns and index names in Pandas is a straightforward operation that offers flexibility in customizing the DataFrame's structure. Whether using the rename() method or directly assigning new values to .columns and .index attributes, data professionals can tailor the DataFrame's labels to enhance data clarity and analytical insights. This ability to rename columns and index names adds to the versatility of Pandas in providing intuitive data manipulation and visualization for effective data-driven solutions.