Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - ตรวจสอบว่า Pandas Index มีเฉพาะค่า boolean

การตรวจสอบว่า Index ประกอบด้วยค่า boolean เท่านั้น

ใช้เมธอด index.is_boolean() ตรวจสอบว่า Index มีเฉพาะค่า True/False เท่านั้น

ขั้นตอน

  1. นำเข้า pandas
  2. สร้าง Index จากค่า boolean
  3. แสดง Index
  4. ใช้ 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