ในการตรวจสอบว่ามีค่า True อย่างน้อยหนึ่งค่าในดัชนี (Index) ให้ใช้เมธอด index.any() ใน Pandas (ค่าที่ไม่ใช่ 0 ถือเป็น True, ค่า 0 ถือเป็น False)
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างดัชนีที่มีค่า True และ False
index = pd.Index([15, 25, 0, 0, 55])
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. ตรวจสอบว่ามีค่า True อย่างน้อยหนึ่งค่า
print("\nCheck whether any element in the index is True...\n", index.any())
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# สร้างดัชนีที่มีค่า True (ไม่ใช่ 0) และ False (เป็น 0)
index = pd.Index([15, 25, 0, 0, 55])
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงรูปร่างของข้อมูล
print("\nA tuple of the shape of underlying data...\n", index.shape)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# ตรวจสอบว่ามีค่า True อย่างน้อยหนึ่งค่า
print("\nCheck whether any element in the index is True...\n", index.any())
ผลลัพธ์
Pandas Index... Int64Index([15, 25, 0, 0, 55], dtype='int64')
A tuple of the shape of underlying data... (5,)
Number of elements in the index... 5
Check whether any element in the index is True... True
คำอธิบาย
เนื่องจากมีค่าที่ไม่ใช่ 0 (15, 25, 55) อย่างน้อยหนึ่งค่า ดังนั้น any() คืนค่า True