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 new column with constant value to Pandas DataFrame
To add a new column with a constant value to a Pandas DataFrame, use the square bracket notation (index operator) and assign the desired value. This operation broadcasts the constant value across all rows in the DataFrame.
Syntax
dataframe['new_column_name'] = constant_value
Creating a Sample DataFrame
First, let's create a DataFrame with sample car data −
import pandas as pd
# Creating a DataFrame with car information
dataFrame = pd.DataFrame({
"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],
"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],
"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],
"Units_Sold": [100, 110, 150, 80, 200, 90]
})
print("Original DataFrame:")
print(dataFrame)
Original DataFrame:
Car Cubic_Capacity Reg_Price Units_Sold
0 Bentley 2000 7000 100
1 Lexus 1800 1500 110
2 BMW 1500 5000 150
3 Mustang 2500 8000 80
4 Mercedes 2200 9000 200
5 Jaguar 3000 6000 90
Adding a Column with Constant Value
Now we'll add a new column called 'Mileage' with a constant value of 15 for all rows −
import pandas as pd
# Creating DataFrame
dataFrame = pd.DataFrame({
"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],
"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],
"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],
"Units_Sold": [100, 110, 150, 80, 200, 90]
})
# Adding new column with constant value
dataFrame['Mileage'] = 15
print("Updated DataFrame with new column:")
print(dataFrame)
Updated DataFrame with new column:
Car Cubic_Capacity Reg_Price Units_Sold Mileage
0 Bentley 2000 7000 100 15
1 Lexus 1800 1500 110 15
2 BMW 1500 5000 150 15
3 Mustang 2500 8000 80 15
4 Mercedes 2200 9000 200 15
5 Jaguar 3000 6000 90 15
Multiple Constant Columns
You can also add multiple columns with different constant values −
import pandas as pd
dataFrame = pd.DataFrame({
"Car": ['Bentley', 'Lexus', 'BMW'],
"Price": [7000, 1500, 5000]
})
# Adding multiple constant columns
dataFrame['Category'] = 'Luxury'
dataFrame['Available'] = True
dataFrame['Rating'] = 4.5
print(dataFrame)
Car Price Category Available Rating
0 Bentley 7000 Luxury True 4.5
1 Lexus 1500 Luxury True 4.5
2 BMW 5000 Luxury True 4.5
Conclusion
Adding a constant value column to a Pandas DataFrame is straightforward using bracket notation. The constant value is automatically broadcasted to all rows, making it an efficient way to add default values or categorical labels to your dataset.
Advertisements
