Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Add a prefix to column names in a Pandas DataFrame
A Pandas DataFrame allows you to add prefixes to all column names using the add_prefix() method. This is useful for distinguishing columns when merging DataFrames or organizing data.
Syntax
DataFrame.add_prefix(prefix)
Parameters:
- prefix ? String to add before each column name
Creating a DataFrame
First, let's create a DataFrame with car data ?
import pandas as pd
# Create 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("Original DataFrame:")
print(dataFrame)
Original 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
Adding Prefix to Column Names
Use add_prefix() to add a prefix to all column names ?
import pandas as pd
# Create 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]
})
# Add prefix to column names
updated_df = dataFrame.add_prefix('column_')
print("DataFrame with prefix:")
print(updated_df)
DataFrame with prefix: 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
Common Use Cases
The add_prefix() method is commonly used when ?
- Merging DataFrames to avoid column name conflicts
- Organizing columns by category or source
- Creating consistent naming conventions
import pandas as pd
# Example: Different prefixes for different datasets
sales_data = pd.DataFrame({
"Q1": [100, 200],
"Q2": [150, 180]
})
budget_data = pd.DataFrame({
"Q1": [120, 190],
"Q2": [160, 170]
})
# Add descriptive prefixes
sales_prefixed = sales_data.add_prefix('sales_')
budget_prefixed = budget_data.add_prefix('budget_')
print("Sales data with prefix:")
print(sales_prefixed)
print("\nBudget data with prefix:")
print(budget_prefixed)
Sales data with prefix: sales_Q1 sales_Q2 0 100 150 1 200 180 Budget data with prefix: budget_Q1 budget_Q2 0 120 160 1 190 170
Conclusion
The add_prefix() method provides a simple way to add prefixes to all DataFrame column names. It returns a new DataFrame without modifying the original, making it ideal for data preparation and organization tasks.
Advertisements
