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

Python Pandas - ตรวจสอบว่าค่าทั้งหมดในดัชนีเป็น True (index.all)

ในการตรวจสอบว่าค่าทั้งหมดในดัชนี (Index) เป็น True ให้ใช้เมธอด index.all() ใน Pandas (ค่าที่ไม่ใช่ 0 ถือเป็น True, ค่า 0 ถือเป็น False)

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้างดัชนี

index = pd.Index([15, 25, 35, 45, 55])

3. แสดงดัชนี

print("Pandas Index...\n", index)

4. ตรวจสอบว่าค่าทั้งหมดเป็น True

print("\nCheck whether all elements are True...\n", index.all())

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd

# สร้างดัชนี
index = pd.Index([15, 25, 35, 45, 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 all elements are True...\n", index.all())

ผลลัพธ์

Pandas Index... Int64Index([15, 25, 35, 45, 55], dtype='int64')
A tuple of the shape of underlying data... (5,)
Number of elements in the index... 5
Check whether all elements are True... True

คำอธิบาย

เนื่องจากค่าทุกค่าในดัชนีไม่ใช่ 0 ทั้งหมด ดังนั้น all() คืนค่า True หากมีค่า 0 อยู่แม้แต่ค่าเดียว จะคืนค่า False