แนวคิด
ใช้ square brackets [] (indexing operator) เลือกคอลัมน์จาก DataFrame สร้าง DataFrame ใหม่ที่มีเฉพาะคอลัมน์ที่ต้องการ
ตัวอย่างโค้ด
import pandas as pd
df = pd.DataFrame({
"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"],
"Opening_Stock": [300, 700, 1200, 1500],
"Closing_Stock": [200, 500, 1000, 900]
})
print("DataFrame:\n", df)
# Subset คอลัมน์เดียว (ต้องใช้ double brackets เพื่อได้ DataFrame)
print("\nSubset คอลัมน์ Product:\n", df[['Product']])
# Subset หลายคอลัมน์
print("\nSubset คอลัมน์ Stock:\n", df[['Opening_Stock', 'Closing_Stock']])
ผลลัพธ์
DataFrame:
Closing_Stock Opening_Stock Product
0 200 300 SmartTV
1 500 700 ChromeCast
2 1000 1200 Speaker
3 900 1500 Earphone
Subset คอลัมน์ Product:
Product
0 SmartTV
1 ChromeCast
2 Speaker
3 Earphone
Subset คอลัมน์ Stock:
Opening_Stock Closing_Stock
0 300 200
1 700 500
2 1200 1000
3 1500 900
หมายเหตุสำคัญ
df['Product']คืน Series (1 มิติ)df[['Product']]คืน DataFrame (2 มิติ) - ใช้ double brackets- ลำดับคอลัมน์ในผลลัพธ์ ตามลำดับในลิสต์ที่ส่งเข้า