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

Python Pandas - ตรวจสอบว่าดัชนีเพิ่มขึ้นอย่างเดี่ยว (is_monotonic_increasing)

ในการตรวจสอบว่าดัชนี (Index) มีค่าเพิ่มขึ้นอย่างเดี่ยว (monotonic increasing) หมายถึงค่าต่อไปเท่ากับหรือมากกว่าค่าก่อนหน้า ให้ใช้คุณสมบัติ index.is_monotonic_increasing

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

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

import pandas as pd

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

index = pd.Index([10, 20, 20, 30, 40])

3. แสดงดัชนี

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

4. ตรวจสอบว่าเพิ่มขึ้นอย่างเดี่ยว

print("\nIs the Pandas index monotonic increasing?\n", index.is_monotonic_increasing)

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

import pandas as pd

# สร้างดัชนี
index = pd.Index([10, 20, 20, 30, 40])

# แสดงดัชนี
print("Pandas Index...\n", index)

# แสดงอาร์เรย์ของข้อมูล
print("\nArray...\n", index.values)

# ตรวจสอบว่าเพิ่มขึ้นอย่างเดี่ยว
print("\nIs the Pandas index monotonic increasing?\n", index.is_monotonic_increasing)

ผลลัพธ์

Pandas Index... Int64Index([10, 20, 20, 30, 40], dtype='int64')
Array... [10 20 20 30 40]
Is the Pandas index monotonic increasing? True

คำอธิบาย

is_monotonic_increasing คืนค่า True หากค่าในดัชนีไม่ลดลง (ค่าต่อไป ≥ ค่าก่อนหน้า) อนุญาตให้มีค่าเท่ากันได้ (20, 20)