Python - Rename column names by index in a Pandas DataFrame without using rename()

PythonServer Side ProgrammingProgramming

We can easily rename a column by index i.e. without using rename(). Import the required library −

import pandas as pd

Create a 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]
   }
)

Let us now rename all the columns using columns.values[0[ by setting the index of the column to be changed in the square brackets −

dataFrame.columns.values[0] = "Car Names"
dataFrame.columns.values[1] = "Registration Cost"
dataFrame.columns.values[2] = "Units_Sold"

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 name
dataFrame.columns.values[0] = "Car Names"
dataFrame.columns.values[1] = "Registration Cost"
dataFrame.columns.values[2] = "Units_Sold"

print"\nUpdated DataFrame with new column names...\n",dataFrame

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 new column names...
   Car Names   Registration Cost   Units_Sold
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:13:51
Advertisements