Skip to content

Commit 49b342b

Browse files
authored
CLN: simplify Categorical comparisons (#36237)
1 parent f8d5fba commit 49b342b

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

pandas/core/arrays/categorical.py

+8-10
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858

5959
def _cat_compare_op(op):
6060
opname = f"__{op.__name__}__"
61+
fill_value = True if op is operator.ne else False
6162

6263
@unpack_zerodim_and_defer(opname)
6364
def func(self, other):
@@ -92,26 +93,23 @@ def func(self, other):
9293
else:
9394
other_codes = other._codes
9495

95-
f = getattr(self._codes, opname)
96-
ret = f(other_codes)
96+
ret = op(self._codes, other_codes)
9797
mask = (self._codes == -1) | (other_codes == -1)
9898
if mask.any():
99-
# In other series, the leads to False, so do that here too
100-
if opname == "__ne__":
101-
ret[(self._codes == -1) & (other_codes == -1)] = True
102-
else:
103-
ret[mask] = False
99+
ret[mask] = fill_value
104100
return ret
105101

106102
if is_scalar(other):
107103
if other in self.categories:
108104
i = self.categories.get_loc(other)
109-
ret = getattr(self._codes, opname)(i)
105+
ret = op(self._codes, i)
110106

111107
if opname not in {"__eq__", "__ge__", "__gt__"}:
112-
# check for NaN needed if we are not equal or larger
108+
# GH#29820 performance trick; get_loc will always give i>=0,
109+
# so in the cases (__ne__, __le__, __lt__) the setting
110+
# here is a no-op, so can be skipped.
113111
mask = self._codes == -1
114-
ret[mask] = False
112+
ret[mask] = fill_value
115113
return ret
116114
else:
117115
return ops.invalid_comparison(self, other, op)

0 commit comments

Comments
 (0)