Skip to content

Commit 556f9c3

Browse files
committed
BUG: Fix Categorical comparsion with Series of dtype 'category'
This is a fix attempt for issue #16659.
1 parent 28622c5 commit 556f9c3

File tree

3 files changed

+17
-4
lines changed

3 files changed

+17
-4
lines changed

doc/source/whatsnew/v0.21.0.txt

+2
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,8 @@ Categorical
304304
^^^^^^^^^^^
305305
- Bug in :func:`Series.isin` when called with a categorical (:issue`16639`)
306306

307+
- Bug in ``Categorical.is_dtype_equal()`` where comparison with Series whose dtype is 'category' is not handled correctly (:issue:`16659`)
308+
307309

308310
Other
309311
^^^^^

pandas/core/categorical.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -1965,16 +1965,22 @@ def is_dtype_equal(self, other):
19651965
19661966
Parameters
19671967
----------
1968-
other : Categorical
1968+
other : Categorical, Series
19691969
19701970
Returns
19711971
-------
19721972
are_equal : boolean
19731973
"""
1974-
19751974
try:
1976-
return (self.categories.equals(other.categories) and
1977-
self.ordered == other.ordered)
1975+
from pandas.core.series import Series
1976+
1977+
if isinstance(other, Series):
1978+
other_categorical = other.values
1979+
else:
1980+
other_categorical = other
1981+
1982+
return (self.categories.equals(other_categorical.categories) and
1983+
self.ordered == other_categorical.ordered)
19781984
except (AttributeError, TypeError):
19791985
return False
19801986

pandas/tests/test_categorical.py

+5
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,11 @@ def test_is_equal_dtype(self):
152152
CategoricalIndex(c1, categories=list('cab'))))
153153
assert not c1.is_dtype_equal(CategoricalIndex(c1, ordered=True))
154154

155+
s1 = pd.Series(c1)
156+
assert c1.is_dtype_equal(s1)
157+
assert not c2.is_dtype_equal(s1)
158+
assert not c3.is_dtype_equal(s1)
159+
155160
def test_constructor(self):
156161

157162
exp_arr = np.array(["a", "b", "c", "a", "b", "c"], dtype=np.object_)

0 commit comments

Comments
 (0)