Skip to content

Commit 1028791

Browse files
authored
BUG: Fix TypeError in assert_index_equal when comparing CategoricalIndex with check_categorical=True and exact=False (#61941)
1 parent ba2cb48 commit 1028791

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,6 +933,7 @@ Bug fixes
933933
Categorical
934934
^^^^^^^^^^^
935935
- Bug in :func:`Series.apply` where ``nan`` was ignored for :class:`CategoricalDtype` (:issue:`59938`)
936+
- Bug in :func:`testing.assert_index_equal` raising ``TypeError`` instead of ``AssertionError`` for incomparable ``CategoricalIndex`` when ``check_categorical=True`` and ``exact=False`` (:issue:`61935`)
936937
- Bug in :meth:`Categorical.astype` where ``copy=False`` would still trigger a copy of the codes (:issue:`62000`)
937938
- Bug in :meth:`DataFrame.pivot` and :meth:`DataFrame.set_index` raising an ``ArrowNotImplementedError`` for columns with pyarrow dictionary dtype (:issue:`53051`)
938939
- Bug in :meth:`Series.convert_dtypes` with ``dtype_backend="pyarrow"`` where empty :class:`CategoricalDtype` :class:`Series` raised an error or got converted to ``null[pyarrow]`` (:issue:`59934`)

pandas/_testing/asserters.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,17 @@ def _check_types(left, right, obj: str = "Index") -> None:
325325
# skip exact index checking when `check_categorical` is False
326326
elif check_exact and check_categorical:
327327
if not left.equals(right):
328-
mismatch = left._values != right._values
328+
# _values compare can raise TypeError (non-comparable
329+
# categoricals (GH#61935)
330+
try:
331+
mismatch = left._values != right._values
332+
except TypeError:
333+
raise_assert_detail(
334+
obj,
335+
"types are not comparable (non-matching categorical categories)",
336+
left,
337+
right,
338+
)
329339

330340
if not isinstance(mismatch, np.ndarray):
331341
mismatch = cast("ExtensionArray", mismatch).fillna(True)

pandas/tests/util/test_assert_index_equal.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,3 +317,11 @@ def test_assert_multi_index_dtype_check_categorical(check_categorical):
317317
tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical)
318318
else:
319319
tm.assert_index_equal(idx1, idx2, check_categorical=check_categorical)
320+
321+
322+
def test_assert_index_equal_categorical_incomparable_categories():
323+
# GH#61935
324+
left = Index([1, 2, 3], name="a", dtype="category")
325+
right = Index([1, 2, 6], name="a", dtype="category")
326+
with pytest.raises(AssertionError, match="types are not comparable"):
327+
tm.assert_index_equal(left, right, check_categorical=True, exact=False)

0 commit comments

Comments
 (0)