Python – Create a new column in a Pandas dataframe

PythonServer Side ProgrammingProgramming

To create a new column, we will use the already created column. At first, let us create a DataFrame and read our CSV −

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

Now, we will create a new column “New_Reg_Price” from the already created column “Reg_Price” and add 100 to each value, forming a new column −

dataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)

Example

Following is the code −

import pandas as pd

# reading csv file
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("DataFrame...\n",dataFrame)

# count the rows and columns in a DataFrame
print("\nNumber of rows and column in our DataFrame = ",dataFrame.shape)

dataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)

print("Updated DataFrame with a new column...\n",dataFrame)

print("\n[Updated] Number of rows and column in our DataFrame = ",dataFrame.shape)

Output

This will produce the following output −

DataFrame...
           Car   Date_of_Purchase   Reg_Price
0          BMW         10/10/2020        1000
1        Lexus         10/12/2020         750
2         Audi         10/17/2020         750
3       Jaguar         10/16/2020        1500
4      Mustang         10/19/2020        1100
5  Lamborghini         10/22/2020        1000

Number of rows and column in our DataFrame = (6, 3)
Updated DataFrame with a new column ...
           Car   Date_of_Purchase   Reg_Price   New_Reg_Price
0          BMW         10/10/2020        1000            1100
1        Lexus         10/12/2020         750             850
2         Audi         10/17/2020         750             850
3       Jaguar         10/16/2020        1500            1600
4      Mustang         10/19/2020        1100            1200
5  Lamborghini         10/22/2020        1000            1100

(Updated)Number of rows and column in our DataFrame = (6, 4)
raja
Published on 28-Sep-2021 10:53:53
Advertisements