วิธีการหลัก
Pandas มีหลายวิธีในการเลือกเฉพาะคอลัมน์ที่ต้องการ (subset columns):
- Indexing operator ([]):
df[['col1', 'col2']] - filter(): กรองคอลัมน์ด้วยชื่อ, regex, หรือ pattern
- loc/iloc: เลือกด้วยตำแหน่งหรือชื่อ
ตัวอย่างโค้ด
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)
# 1. เลือกคอลัมน์เดียว
print("\nคอลัมน์ Product:\n", df[['Product']])
# 2. เลือกหลายคอลัมน์
print("\nคอลัมน์ Stock:\n", df[['Opening_Stock', 'Closing_Stock']])
# 3. ใช้ filter() กรองชื่อคอลัมน์ที่มี 'Open'
print("\nfilter(like='Open'):\n", df.filter(like='Open'))
# 4. ใช้ filter() กรองด้วย regex
print("\nfilter(regex='_Stock$'):\n", df.filter(regex='_Stock$'))
# 5. ใช้ filter() กรองคอลัมน์ที่ขึ้นต้นด้วย 'C'
print("\nfilter(regex='^C'):\n", df.filter(regex='^C'))
ผลลัพธ์
DataFrame:
Closing_Stock Opening_Stock Product
0 200 300 SmartTV
1 500 700 ChromeCast
2 1000 1200 Speaker
3 900 1500 Earphone
คอลัมน์ Product:
Product
0 SmartTV
1 ChromeCast
2 Speaker
3 Earphone
คอลัมน์ Stock:
Opening_Stock Closing_Stock
0 300 200
1 700 500
2 1200 1000
3 1500 900
filter(like='Open'):
Opening_Stock
0 300
1 700
2 1200
3 1500
filter(regex='_Stock$'):
Opening_Stock Closing_Stock
0 300 200
1 700 500
2 1200 1000
3 1500 900
filter(regex='^C'):
Closing_Stock
0 200
1 500
2 1000
3 900
สรุปพารามิเตอร์ filter()
| พารามิเตอร์ | คำอธิบาย |
|---|---|
like | เลือกคอลัมน์ที่มี substring นี้ |
regex | เลือกคอลัมน์ที่ตรงกับ regular expression |
items | เลือกคอลัมน์จากรายการที่กำหนด |
axis | 0=แถว, 1=คอลัมน์ (ค่าเริ่มต้นคือคอลัมน์) |