บทนำ
การเพิ่มคอลัมน์ใหม่ที่มีค่าเป็นศูนย์ (0) ทุกแถว ใน Pandas DataFrame ทำได้ง่ายด้วยการ assignment ตรงไปตรงมา
วิธีพื้นฐาน
import pandas as pd
df = pd.DataFrame({
"Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],
"Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],
"Roll Number": [5, 10, 3, 8, 2, 9, 6]
})
print("DataFrame ต้นทาง:")
print(df)
# เพิ่มคอลัมน์ศูนย์
df['ZeroColumn'] = 0
print("\nDataFrame หลังเพิ่ม ZeroColumn:")
print(df)
ผลลัพธ์
DataFrame ต้นทาง:
Student Result Roll Number
0 Jack Pass 5
1 Robin Fail 10
2 Ted Pass 3
3 Marc Fail 8
4 Scarlett Pass 2
5 Kat Pass 9
6 John Pass 6
DataFrame หลังเพิ่ม ZeroColumn:
Student Result Roll Number ZeroColumn
0 Jack Pass 5 0
1 Robin Fail 10 0
2 Ted Pass 3 0
3 Marc Fail 8 0
4 Scarlett Pass 2 0
5 Kat Pass 9 0
6 John Pass 6 0
การเพิ่มคอลัมน์แบบต่างๆ
| โค้ด | ผลลัพธ์ | คำอธิบาย |
|---|---|---|
df['new'] = 0 | int 0 | Scalar broadcasting |
df['new'] = 0.0 | float 0.0 | Scalar broadcasting |
df['new'] = [0]*len(df) | list of 0 | Explicit list |
df['new'] = np.zeros(len(df)) | numpy array | เร็วสำหรับข้อมูลใหญ่ |
df['new'] = pd.Series(0, index=df.index) | Series | Index aligned |
df.insert(loc, 'new', 0) | int 0 | ระบุตำแหน่งคอลัมน์ |
ตัวอย่าง: insert() ระบุตำแหน่ง
# แทรกคอลัมน์ที่ตำแหน่ง 1 (หลัง Student)
df.insert(1, 'ZeroCol', 0)
print(df.columns.tolist())
# ['Student', 'ZeroCol', 'Result', 'Roll Number', 'ZeroColumn']
กรณีใช้งานจริง
- สร้างคอลัมน์ placeholder สำหรับคำนวณภายหลัง
- Initialize counter column
- เพิ่ม feature column สำหรับ ML (zero-filled)
- สร้าง dummy column สำหรับ one-hot encoding base
ข้อควรระวัง
- Assignment แบบ scalar (
df['col'] = 0) ใช้ broadcasting - เร็วและประหยัดหน่วยความจำ - ถ้าต้องการค่าแตกต่างต่อแถว ให้ใช้ list/array/Series ที่มีความยาวเท่ากับ df
insert()แก้ไข inplace ไม่คืนค่า DataFrame ใหม่
สรุป
ใช้ df['column_name'] = 0 สำหรับเพิ่มคอลัมน์ศูนย์แบบง่ายที่สุด ใช้ df.insert(loc, 'name', 0) หากต้องการควบคุมตำแหน่งคอลัมน์ ทั้งคู่ทำงานผ่าน broadcasting mechanism ของ Pandas