Python - 在 Pandas 数据框中创建一个新列
要创建新列,我们将使用已创建的列。首先,让我们创建一个DataFrame并读取我们的CSV-
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
现在,我们将从已经创建的列“Reg_Price”创建一个新列“New_Reg_Price”,并为每个值添加100,形成一个新列-
dataFrame['New_Reg_Price'] = (dataFrame['Reg_Price'] + 100)
示例
以下是代码-
import pandas as pd #readingcsvfile dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv") print("DataFrame...\n",dataFrame) #counttherowsandcolumnsinaDataFrame 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)输出结果
这将产生以下输出-
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)