Skip to content

Commit fa77cec

Browse files
committed
BUG: Fix assert_series_equal for categoricals with nulls and check_category_order=False (#62008)
1 parent 355b143 commit fa77cec

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

pandas/_testing/asserters.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -495,8 +495,15 @@ def assert_categorical_equal(
495495
lc, rc = left.categories, right.categories
496496
assert_index_equal(lc, rc, obj=f"{obj}.categories", exact=exact)
497497
assert_index_equal(
498-
left.categories.take(left.codes),
499-
right.categories.take(right.codes),
498+
Index(
499+
[left.categories[code] if code >= 0 else np.nan for code in left.codes]
500+
),
501+
Index(
502+
[
503+
right.categories[code] if code >= 0 else np.nan
504+
for code in right.codes
505+
]
506+
),
500507
obj=f"{obj}.values",
501508
exact=exact,
502509
)

pandas/tests/util/test_assert_categorical_equal.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import numpy as np
12
import pytest
23

34
from pandas import Categorical
@@ -86,3 +87,14 @@ def test_categorical_equal_object_override(obj):
8687

8788
with pytest.raises(AssertionError, match=msg):
8889
tm.assert_categorical_equal(c1, c2, obj=obj)
90+
91+
92+
def test_categorical_equal_with_nans_and_different_order():
93+
values = ["B", np.nan, "D"]
94+
categories_left = ["B", "D"]
95+
categories_right = categories_left[::-1]
96+
97+
left = Categorical(values, categories=categories_left)
98+
right = Categorical(values, categories=categories_right)
99+
100+
tm.assert_categorical_equal(left, right, check_category_order=False)

0 commit comments

Comments
 (0)