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 # 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
输出
这将产生以下输出 −
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
广告