Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Pandas - 두 개의 CategoricalIndex 객체에 동일한 요소가 포함되어 있는지 확인하는 방법

두 개의 CategoricalIndex 객체에 동일한 요소가 포함되어 있는지 확인하려면 Pandas에서 제공하는 equals() 메서드를 사용합니다. 이 메서드는 두 인덱스의 요소뿐만 아니라 카테고리 구성과 순서 정보까지 비교하여 완전히 같으면 True를 반환합니다.

먼저 필요한 라이브러리를 임포트합니다.

import pandas as pd

CategoricalIndex 객체 생성하기

categories 매개변수를 사용하여 범주형 데이터의 카테고리를 설정하고, ordered 매개변수를 사용하여 해당 범주형을 순서가 있는(ordered) 형태로 지정할 수 있습니다.

아래와 같이 두 개의 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"])

equals()로 동등성 검사하기

생성된 두 CategoricalIndex 객체가 서로 같은지 equals() 메서드로 확인합니다.

print("\n두 CategoricalIndex 객체의 동일 여부 확인...\n", catIndex1.equals(catIndex2))

전체 예제 코드

다음은 지금까지 설명한 내용을 모두 포함한 전체 코드입니다.

import pandas as pd

# categories 매개변수로 카테고리 설정
# ordered 매개변수로 순서가 있는 범주형으로 지정
# 두 개의 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"])

# CategoricalIndex 객체 출력
print("CategoricalIndex1...\n", catIndex1)
print("\nCategoricalIndex2...\n", catIndex2)

# 두 CategoricalIndex 객체의 동일 여부 확인
print("\n두 CategoricalIndex 객체의 동일 여부 확인...\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')

두 CategoricalIndex 객체의 동일 여부 확인...
True

정리

equals() 메서드는 단순히 요소 값만 비교하는 것이 아니라, 카테고리 목록과 순서(ordered) 속성까지 함께 비교한다는 점이 중요합니다. 따라서 요소 값이 같더라도 카테고리 정의나 순서 속성이 다르면 False가 반환됩니다. 두 CategoricalIndex 객체가 완전히 동일한지 엄격하게 검증해야 할 때 이 메서드를 활용하면 됩니다.