
- 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
Rename column name with an index number of the CSV file in Pandas
Using columns.values(), we can easily rename column name with index number of a CSV file.
Let’s say the following are the contents of our CSV file opened in Microsoft Excel −
We will rename the column names. At first, load data from a CSV file into a Pandas DataFrame −
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesData.csv")
Display all the column names from the CSV −
dataFrame.columns
Now, rename column names −
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 # Load data from a CSV file into a Pandas DataFrame: dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesData.csv") print("Reading the CSV file...\n",dataFrame) # displaying column names res = dataFrame.columns # displaying another subset print("\nDisplaying column names : \n",res) # rename column names from the CSV file dataFrame.columns.values[0] = "Car Names" dataFrame.columns.values[1] = "Registration Cost" dataFrame.columns.values[2] = "Units Sold" print("\nDisplaying updated column names : \n",res)
Output
This will produce the following output −
Reading the CSV file... Car Reg_Price Units 0 BMW 2500 100 1 Lexus 3500 80 2 Audi 2500 120 3 Jaguar 2000 70 4 Mustang 2500 110 Displaying column names : Index(['Car','Reg_Price','Units'], dtype='object') Displaying updated column names : Index(['Car Names','Registration Cost','Units Sold'], dtype='object')
- Related Articles
- Python - Rename column names by index in a Pandas DataFrame without using rename()
- Python - Read csv file with Pandas without header?
- Rename column name in MySQL?
- How to get column index from column name in Python Pandas?
- How to read a Pandas CSV file with no header?
- Python Pandas- Create multiple CSV files from existing CSV file
- Writing a Pandas DataFrame to CSV file
- How to rename column names in a Pandas DataFrame?
- Python - How to rename multiple column headers in a Pandas DataFrame with Dictionary?
- Python Pandas - Set index name for an already created Index object
- Python Pandas - Set the name of the index
- C program to change the file name using rename() function
- Python Pandas - Alter index name
- Python Pandas CategoricalIndex - Rename categories with lambda
- Python - How to write pandas dataframe to a CSV file

Advertisements