Python - Add a new column with constant value to Pandas DataFrame

PythonServer Side ProgrammingProgramming

To add anew column with constant value, use the square bracket i.e. the index operator and set that value.

At first, import the required library −

import pandas as pd

Creating a DataFrame with 4 columns −

dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BBMW', '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 a new column with a constant value. The new column names is set in the square bracket −

dataFrame['Mileage'] = 15

Example

Following is the complete code −

import pandas as pd

# creating dataframe
dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BBMW', '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"Dataframe...\n",dataFrame

# adding new column with a constant value
dataFrame['Mileage'] = 15

print"\nUpdated Dataframe with a new column...\n",dataFrame

Output

This will produce the following output −

Dataframe...
        Car   Cubic_Capacity   Reg_Price   Units_Sold
0   Bentley             2000        7000          100
1     Lexus             1800        1500          110
2      BBMW             1500        5000          150
3   Mustang             2500        8000           80
4  Mercedes             2200        9000          200
5    Jaguar             3000        6000           90

Updated Dataframe with a new column...
        Car   Cubic_Capacity   Reg_Price   Units_Sold   Mileage
0   Bentley             2000        7000          100        15
1     Lexus             1800        1500          110        15
2      BBMW             1500        5000          150        15
3   Mustang             2500        8000           80        15
4  Mercedes             2200        9000          200        15
5    Jaguar             3000        6000           90        15
raja
Published on 22-Sep-2021 11:41:48
Advertisements