Renaming column names – Python Pandas

PythonServer Side ProgrammingProgramming

We can use the rename() method to rename column names. Let’s say the following is our Pandas DataFrame with 3 columns −

dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130]
   }
)

We will rename two columns i.e. “Car” to “Car Names” and “Reg_Price” to “Registration Cost”:

dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'})

Example

Following is the code −

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units": [90, 120, 100, 150, 200, 130]
   }
)

print"DataFrame ...\n",dataFrame

# Renaming columns
res = dataFrame.rename(columns={dataFrame.columns[0]: 'Car Names', dataFrame.columns[1]: 'Registration Cost'})

print"\nUpdated DataFrame with renamed column names...\n",res

Output

This will produce the following output −

DataFrame ...
        Car   Reg_Price   Units
0       BMW        7000      90
1     Lexus        1500     120
2     Tesla        5000     100
3   Mustang        8000     150
4  Mercedes        9000     200
5    Jaguar        6000     130

Updated DataFrame with renamed column names...
  Car Names   Registration Cost   Units
0       BMW                7000      90
1     Lexus                1500     120
2     Tesla                5000     100
3   Mustang                8000     150
4  Mercedes                9000     200
5    Jaguar                6000     130
raja
Published on 20-Sep-2021 07:21:18
Advertisements