Skip to content

BUG: Fix TypeError in assert_index_equal when comparing CategoricalIndex with check_categorical=True and exact=False #61941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion pandas/_testing/asserters.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import pandas as pd
from pandas import (
Categorical,
CategoricalIndex,
DataFrame,
DatetimeIndex,
Index,
Expand Down Expand Up @@ -322,7 +323,15 @@ def _check_types(left, right, obj: str = "Index") -> None:
# skip exact index checking when `check_categorical` is False
elif check_exact and check_categorical:
if not left.equals(right):
mismatch = left._values != right._values
try:
mismatch = left._values != right._values
except TypeError:
if isinstance(left, CategoricalIndex) and isinstance(
right, CategoricalIndex
):
mismatch = left.codes != right.codes
else:
mismatch = left.values != right.values

if not isinstance(mismatch, np.ndarray):
mismatch = cast("ExtensionArray", mismatch).fillna(True)
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/util/test_assert_index_equal.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,15 @@ def test_assert_multi_index_dtype_check_categorical(check_categorical):
tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical)
else:
tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical)


def test_assert_index_equal_categorical_mismatch_categories():
# GH#61941
ci = CategoricalIndex(["a", "b", "c"], categories=["a", "b", "c"], ordered=False)
idx = Index(["a", "b", "c"])

with pytest.raises(AssertionError, match="Index are different"):
tm.assert_index_equal(
ci,
idx,
)
Loading