Python - 向 Pandas DataFrame 添加具有常量值的新列
要添加具有常量值的新列,请使用方括号即索引运算符并设置该值。
首先,导入所需的库-
import pandas as pd
创建一个有4列的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] })
添加具有常量值的新列。新列名设置在方括号中-
dataFrame['Mileage'] = 15
示例
以下是完整的代码-
import pandas as pd #创建数据框 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 #添加具有常量值的新列 dataFrame['Mileage'] = 15 print"\nUpdated Dataframe with a new column...\n",dataFrame输出结果
这将产生以下输出-
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