Python - Renaming the columns of Pandas DataFrame


To rename the columns of a DataFrame, use the rename() method. Set the column names you want to rename under the “columns” parameter of the rename() method. For example, changing “Car” column to “Car Name” −

dataFrame.rename(columns={'Car': 'Car Name'}, inplace=False)

At first, read the CSV and create a DataFrame −

dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesRecords.csv")

Now, rename the column names. Here, we are renaming the columns “Car”, “Date_of_Purchase” and “Reg_Price” −

dataFrame = dataFrame.rename(columns={'Car': 'Car Name', 'Date_of_Purchase': 'Sold On', 'Reg_Price' : 'Booking Price'}, inplace=False)

Example

Following is the code

import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesRecords.csv")
print("DataFrame...\n",dataFrame)

# count the rows and columns in a DataFrame
print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape)

dataFrame = dataFrame.rename(columns={'Car': 'Car Name', 'Date_of_Purchase': 'Sold On', 'Reg_Price' : 'Booking Price'}, inplace=False)
print("\nDataFrame with updated Column Name ...\n",dataFrame)

Output

This will produce the following output −

DataFrame...
           Car   Date_of_Purchase   Reg_Price
0          BMW         10/10/2020        1000
1        Lexus         10/12/2020         750
2         Audi         10/17/2020         750
3       Jaguar         10/16/2020        1500
4      Mustang         10/19/2020        1100
5  Lamborghini         10/22/2020        1000

Number of rows and column in our DataFrame = (6, 3)

DataFrame with updated Column Name ...
      Car Name     Sold On   Booking Price
0          BMW  10/10/2020            1000
1        Lexus  10/12/2020             750
2         Audi  10/17/2020             750
3       Jaguar  10/16/2020            1500
4      Mustang  10/19/2020            1100
5  Lamborghini  10/22/2020            1000

Updated on: 27-Sep-2021

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements