
- 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 - Add a prefix to column names in a Pandas DataFrame
To add a prefix to all the column names, use the add_prefix() method. At first, import the required Pandas library −
import pandas as pd
Create a DataFrame with 4 columns −
dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250] })
Add a prefix to _column to every column using add_prefix() −
dataFrame.add_prefix('column_')
Example
Following is the code −
import pandas as pd # creating dataframe dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250] }) print"DataFrame ...\n",dataFrame print"\nUpdated DataFrame...\n",dataFrame.add_prefix('column_')
Output
This will produce the following output −
DataFrame ... Car Cubic_Capacity Reg_Price Units_Sold 0 BMW 2000 7000 100 1 Lexus 1800 1500 120 2 Tesla 1500 5000 150 3 Mustang 2500 8000 110 4 Mercedes 2200 9000 200 5 Jaguar 3000 6000 250 Updated DataFrame... column_Car column_Cubic_Capacity column_Reg_Price column_Units_Sold 0 BMW 2000 7000 100 1 Lexus 1800 1500 120 2 Tesla 1500 5000 150 3 Mustang 2500 8000 110 4 Mercedes 2200 9000 200 5 Jaguar 3000 6000 250
- Related Articles
- Python - Add a zero column to Pandas DataFrame
- Python Pandas – Display all the column names in a DataFrame
- How to rename column names in a Pandas DataFrame?
- Python - Add a new column with constant value to Pandas DataFrame
- Python - Change column names and row indexes in Pandas DataFrame
- Python - Rename column names by index in a Pandas DataFrame without using rename()
- How to lowercase the column names in Pandas dataframe?
- Python – Create a new column in a Pandas dataframe
- Apply uppercase to a column in Pandas dataframe in Python
- How to add column from another DataFrame in Pandas?
- Python - How to select a column from a Pandas DataFrame
- Python - Stacking a multi-level column in a Pandas DataFrame
- Adding a new column to existing DataFrame in Pandas in Python
- Renaming column names – Python Pandas
- Adding a new column to an existing DataFrame in Python Pandas

Advertisements