การตรวจสอบว่า Index ประกอบด้วยค่า boolean เท่านั้น
ใช้เมธอด index.is_boolean() ตรวจสอบว่า Index มีเฉพาะค่า True/False เท่านั้น
ขั้นตอน
- นำเข้า pandas
- สร้าง Index จากค่า boolean
- แสดง Index
- ใช้
is_boolean()ตรวจสอบ
ตัวอย่างโค้ด
import pandas as pd
# สร้าง Index boolean
index = pd.Index([True, True, False, False, True, True, True])
# แสดง Index
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบและ dtype
print("\nNumber of elements in the index...\n", index.size)
print("\nThe dtype object...\n", index.dtype)
# ตรวจสอบว่าเป็น boolean เท่านั้น
print("\nIndex values only consists of booleans?\n", index.is_boolean())
ผลลัพธ์
Pandas Index... Index([True, True, False, False, True, True, True], dtype='object') Number of elements in the index... 7 The dtype object... object Index values only consists of booleans? True
หมายเหตุ
แม้ dtype จะเป็น 'object' (เพราะ boolean ใน Python เป็น subclass ของ int) แต่ is_boolean() ตรวจสอบค่าจริงและคืนค่า True