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

更新日期: 22-09-2021

5K+ 瀏覽量

助力你的 事業

完成課程認證

開始學習
廣告
© . All rights reserved.