Skip to content

Commit da692c1

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

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
@@ -130,6 +130,8 @@ Numeric
130130
Categorical
131131
^^^^^^^^^^^
132132

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

134136
Other
135137
^^^^^

pandas/core/categorical.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -1995,16 +1995,22 @@ def is_dtype_equal(self, other):
19951995
19961996
Parameters
19971997
----------
1998-
other : Categorical
1998+
other : Categorical, Series
19991999
20002000
Returns
20012001
-------
20022002
are_equal : boolean
20032003
"""
2004-
20052004
try:
2006-
return (self.categories.equals(other.categories) and
2007-
self.ordered == other.ordered)
2005+
from pandas.core.series import Series
2006+
2007+
if isinstance(other, Series):
2008+
other_categorical = other.values
2009+
else:
2010+
other_categorical = other
2011+
2012+
return (self.categories.equals(other_categorical.categories) and
2013+
self.ordered == other_categorical.ordered)
20082014
except (AttributeError, TypeError):
20092015
return False
20102016

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)