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

PythonServer Side ProgrammingProgramming

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
raja
Published on 18-Oct-2021 07:21:39
Advertisements