Python Pandas - Determine if two CategoricalIndex objects contain the same elements


To determine if two CategoricalIndex objects contain the same elements, use the equals() method. At first, import the required libraries −

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"])

Check both the CategoricalIndex objects for equality −

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

Example

Following is the code −

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

Output

This will produce the following output −

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

Updated on: 18-Oct-2021

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements