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

เปรียบเทียบ CategoricalIndex ว่ามีองค์ประกอบเหมือนกันหรือไม่ ด้วย equals()

เมธอด equals() ของ CategoricalIndex ใช้ตรวจสอบว่าสองดัชนีมีค่า ความเรียงลำดับ และหมวดหมู่ (categories) เหมือนกันทุกประการหรือไม่ คืนค่า True หรือ False

ตัวอย่างโค้ด

import pandas as pd

# สร้าง CategoricalIndex สองชุด ที่เหมือนกันทุกประการ
catIndex1 = pd.CategoricalIndex(
    ["p", "q", "r", "s", "p", "q", "r", "s"],
    ordered=True,
    categories=["p", "q", "r", "s"]
)
catIndex2 = pd.CategoricalIndex(
    ["p", "q", "r", "s", "p", "q", "r", "s"],
    ordered=True,
    categories=["p", "q", "r", "s"]
)

print("CategoricalIndex1:\n", catIndex1)
print("\nCategoricalIndex2:\n", catIndex2)

# ตรวจสอบความเท่ากัน
print("\nเท่ากันหรือไม่?\n", catIndex1.equals(catIndex2))

ผลลัพธ์

CategoricalIndex1:
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

CategoricalIndex2:
CategoricalIndex(['p', 'q', 'r', 's', 'p', 'q', 'r', 's'], categories=['p', 'q', 'r', 's'], ordered=True, dtype='category')

เท่ากันหรือไม่?
True

ทั้งสองดัชนีเหมือนกันทั้งค่า ลำดับ และการตั้งค่าหมวดหมู่ จึงคืนค่า True