แนวคิดหลัก
Pandas อนุญาตให้กรองข้อมูลใน DataFrame ได้โดยใช้ตัวดำเนินการเปรียบเทียบ (comparison operators) บนคอลัมน์ต่างๆ เช่น >, <, ==, != ผลลัพธ์จะเป็น Series แบบ Boolean (True/False) ซึ่งสามารถนำไปใช้ในการดัชนี (indexing) หรือรวมเงื่อนไขหลายข้อด้วย & (AND), | (OR)
ขั้นตอน
- สร้าง DataFrame ตัวอย่าง
- แสดง DataFrame เดิม
- กำหนดชื่อคอลัมน์ที่ต้องการทดสอบ
- ใช้ตัวดำเนินการเปรียบเทียบต่างๆ
- แสดงผลลัพธ์ Boolean Series
ตัวอย่างโค้ด
import pandas as pd
df = pd.DataFrame({
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
})
print("Input DataFrame:\n", df)
col = "x"
print(f"\nElements > 5 in column {col}:\n", df[col] > 5)
print(f"Elements == 5 in column {col}:\n", df[col] == 5)
col = "y"
print(f"\nElements < 5 in column {col}:\n", df[col] < 5)
print(f"Elements != 5 in column {col}:\n", df[col] != 5)
ผลลัพธ์
Input DataFrame:
x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1
Elements > 5 in column x:
0 False
1 False
2 True
3 False
Name: x, dtype: bool
Elements == 5 in column x:
0 True
1 False
2 False
3 False
Name: x, dtype: bool
Elements < 5 in column y:
0 True
1 False
2 False
3 True
Name: y, dtype: bool
Elements != 5 in column y:
0 True
1 True
2 False
3 True
Name: y, dtype: bool
การประยุกต์ใช้จริง
Boolean Series นี้สามารถนำไปกรองแถวข้อมูลได้โดยตรง:
# เลือกแถวที่คอลัมน์ x มากกว่า 5
filtered = df[df['x'] > 5]
# รวมเงื่อนไขหลายข้อ (x > 2 และ y < 6)
filtered = df[(df['x'] > 2) & (df['y'] < 6)]