Computer >> Máy Tính >  >> Lập trình >> Python

Python Pandas - Xác định xem hai đối tượng CategoricalIndex có chứa các phần tử giống nhau hay không

Để xác định xem hai đối tượng CategoricalIndex có chứa các phần tử giống nhau hay không, hãy sử dụng equals () phương pháp. Đầu tiên, hãy nhập các thư viện được yêu cầu -

import pandas as pd

Đặt danh mục cho danh mục bằng cách sử dụng tham số "danh mục". Xử lý phân loại theo thứ tự bằng cách sử dụng tham số "có thứ tự". Tạo hai đối tượng 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"])

Kiểm tra cả hai đối tượng CategoricalIndex xem có bằng nhau -

print("\nCheck both the CategoricalIndex objects for equality...\n",catIndex1.equals(catIndex2))

Ví dụ

Sau đây là mã -

import pandas as pd

# Set the categories for the categorical using the "categories" parameter
# Treat the categorical as ordered using the "ordered" parameter
# Create two CategoricalIndex objects
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"])

# Display the CategoricalIndex objects
print("CategoricalIndex1...\n",catIndex1)
print("\nCategoricalIndex2...\n",catIndex2)

# Check both the CategoricalIndex objects for equality
print("\nCheck both the CategoricalIndex objects for equality...\n",catIndex1.equals(catIndex2))

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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')

Check both the CategoricalIndex objects for equality...
True