
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Rename column names by index in a Pandas DataFrame without using rename()
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
- Related Articles
- How to rename column names in a Pandas DataFrame?
- Python - How to rename multiple column headers in a Pandas DataFrame with Dictionary?
- Python Pandas CategoricalIndex - Rename categories
- Rename column name with an index number of the CSV file in Pandas
- Rename a table in MySQL using RENAME TABLE command
- Python Pandas CategoricalIndex - Rename categories with lambda
- Python Pandas – Display all the column names in a DataFrame
- Rename multiple files using Python
- How to display Pandas Dataframe in Python without Index?
- Python - Add a prefix to column names in a Pandas DataFrame
- Rename column name in MySQL?
- Write a Python code to rename the given axis in a dataframe
- How to rename a file using Python?
- Python - Change column names and row indexes in Pandas DataFrame
- How to rename directory using Python?

Advertisements