Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - เพิ่มคอลัมน์ใหม่ด้วยค่าคงที่ (Constant Value) ใน Pandas DataFrame

การเพิ่มคอลัมน์ใหม่พร้อมกำหนด ค่าคงที่ (Constant Value)** ให้ทุกแถว ทำได้ง่ายด้วย Index Operator df['new_col'] = value Pandas จะ Broadcast ค่านั้นไปทุกแถวอัตโนมัติ

ขั้นตอนการทำงาน

1. สร้าง DataFrame

import pandas as pd

dataFrame = pd.DataFrame({
    "Car": ['Bentley', 'Lexus', 'BMW', '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]
})

2. เพิ่มคอลัมน์ Mileage = 15 (ค่าคงที่)

dataFrame['Mileage'] = 15
print(dataFrame)

โค้ดตัวอย่างสมบูรณ์

import pandas as pd

dataFrame = pd.DataFrame({
    "Car": ['Bentley', 'Lexus', 'BMW', '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 new column:\n", dataFrame)

ผลลัพธ์

DataFrame:
        Car  Cubic_Capacity  Reg_Price  Units_Sold
0   Bentley            2000       7000         100
1     Lexus            1800       1500         110
2       BMW            1500       5000         150
3   Mustang            2500       8000          80
4  Mercedes            2200       9000         200
5    Jaguar            3000       6000          90

Updated DataFrame:
        Car  Cubic_Capacity  Reg_Price  Units_Sold  Mileage
0   Bentley            2000       7000         100        15
1     Lexus            1800       1500         110        15
2       BMW            1500       5000         150        15
3   Mustang            2500       8000          80        15
4  Mercedes            2200       9000         200        15
5    Jaguar            3000       6000          90        15

Broadcasting ของค่าคงที่

  • Scalar (int, float, str) → Broadcast ไปทุกแถว
  • List/Array ความยาวเท่ากับแถว → Assign ตรงตำแหน่ง
  • Series พร้อม index ตรงกัน → Align ตาม index

ตัวอย่างค่าคงที่ประเภทต่างๆ

# String constant
df['Status'] = 'Active'

# Datetime constant
df['Created_Date'] = pd.Timestamp('2024-01-01')

# Boolean constant
df['Is_Valid'] = True

# None/NaN constant
df['Notes'] = None
df['Score'] = np.nan

# Object constant (list/dict) → ทุกแถวอ้างอิง object เดียวกัน! ⚠️
df['Config'] = {'default': True}  # อันตราย: mutable shared reference

# ใช้ factory function แทน
df['Config'] = df.apply(lambda _: {'default': True}, axis=1)

วิธีอื่น: assign() (Method Chaining)

# Return DataFrame ใหม่ ไม่แก้ไขต้นฉบับ
df = df.assign(Mileage=15, Status='Active')

# ใช้ lambda เข้าถึงคอลัมน์อื่น
df = df.assign(
    Price_Per_Unit=lambda x: x['Reg_Price'] / x['Units_Sold'],
    High_End=lambda x: x['Reg_Price'] > 5000
)

⚠️ ข้อควรระวัง

  • Mutable objects (list, dict) เป็นค่าคงที่ → ทุกแถว share reference เดียวกัน
  • SettingWithCopyWarning: ตรวจสอบว่า DataFrame ไม่ใช่ view
  • ใช้ df.copy() ก่อนแก้ไขถ้าจำเป็น