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

Python Pandas - ตรวจสอบว่าดัชนีลดลงอย่างเดี่ยว (is_monotonic_decreasing)

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

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

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

import pandas as pd

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

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

3. แสดงดัชนี

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

4. ตรวจสอบว่าลดลงอย่างเดี่ยว

print("\nIs the Pandas index monotonic decreasing?\n", index.is_monotonic_decreasing)

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

import pandas as pd

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

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

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

# ตรวจสอบว่าลดลงอย่างเดี่ยว
print("\nIs the Pandas index monotonic decreasing?\n", index.is_monotonic_decreasing)

ผลลัพธ์

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

คำอธิบาย

is_monotonic_decreasing คืนค่า True หากค่าในดัชนีไม่เพิ่มขึ้น (ค่าต่อไป ≤ ค่าก่อนหน้า) อนุญาตให้มีค่าเท่ากันได้ (30, 30, 30)