Rename Columns in a Pandas DataFrame

Rename Columns lets you change existing column names to new ones, making your DataFrame easier to understand and work with. Use the rename() to allow you to specify a dictionary mapping old column names to new ones.

Let us see an example to rename columns in a Pandas DataFrame:

import pandas as pd

df = pd.DataFrame({'A':[1,2], 'B':[3,4]})
df.rename(columns={'A':'col1', 'B':'col2'}, inplace=True)
print(df)

Output

    col1  col2
0     1     3
1     2     4

The above code creates a DataFrame with columns ‘A‘ and ‘B‘, then renames them to ‘col1‘ and ‘col2‘ respectively using the rename() method.

The inplace=True argument modifies the original DataFrame directly. Using inplace=True in df.rename() modifies the existing DataFrame directly rather than creating a new one


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others:


For Videos, Join Our YouTube Channel: Join Now


Read More:

Top Pandas Interview Questions and Answers (MCQs)
Drop a Column from a Pandas DataFrame
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment