Skip to content

Commit 7d16224

Browse files
authored
CLN: re-use invalid_comparison in Categorical comparisons (#36229)
1 parent ab342c6 commit 7d16224

File tree

3 files changed

+7
-18
lines changed

3 files changed

+7
-18
lines changed

pandas/core/arrays/categorical.py

+1-9
Original file line numberDiff line numberDiff line change
@@ -119,15 +119,7 @@ def func(self, other):
119119
ret[mask] = False
120120
return ret
121121
else:
122-
if opname == "__eq__":
123-
return np.zeros(len(self), dtype=bool)
124-
elif opname == "__ne__":
125-
return np.ones(len(self), dtype=bool)
126-
else:
127-
raise TypeError(
128-
f"Cannot compare a Categorical for op {opname} with a "
129-
"scalar, which is not a category."
130-
)
122+
return ops.invalid_comparison(self, other, op)
131123
else:
132124
# allow categorical vs object dtype array comparisons for equality
133125
# these are only positional comparisons

pandas/tests/arrays/categorical/test_operators.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -171,17 +171,14 @@ def test_comparison_with_unknown_scalars(self):
171171
# for unequal comps, but not for equal/not equal
172172
cat = Categorical([1, 2, 3], ordered=True)
173173

174-
msg = (
175-
"Cannot compare a Categorical for op __{}__ with a scalar, "
176-
"which is not a category"
177-
)
178-
with pytest.raises(TypeError, match=msg.format("lt")):
174+
msg = "Invalid comparison between dtype=category and int"
175+
with pytest.raises(TypeError, match=msg):
179176
cat < 4
180-
with pytest.raises(TypeError, match=msg.format("gt")):
177+
with pytest.raises(TypeError, match=msg):
181178
cat > 4
182-
with pytest.raises(TypeError, match=msg.format("gt")):
179+
with pytest.raises(TypeError, match=msg):
183180
4 < cat
184-
with pytest.raises(TypeError, match=msg.format("lt")):
181+
with pytest.raises(TypeError, match=msg):
185182
4 > cat
186183

187184
tm.assert_numpy_array_equal(cat == 4, np.array([False, False, False]))

pandas/tests/series/test_arithmetic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -501,7 +501,7 @@ def test_unequal_categorical_comparison_raises_type_error(self):
501501
# for unequal comps, but not for equal/not equal
502502
cat = Series(Categorical(list("abc"), ordered=True))
503503

504-
msg = "Cannot compare a Categorical for op.+with a scalar"
504+
msg = "Invalid comparison between dtype=category and str"
505505
with pytest.raises(TypeError, match=msg):
506506
cat < "d"
507507
with pytest.raises(TypeError, match=msg):

0 commit comments

Comments
 (0)