Skip to content

CLN: simplify Categorical comparisons #36237

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 11, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@

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

@unpack_zerodim_and_defer(opname)
def func(self, other):
Expand Down Expand Up @@ -97,26 +98,23 @@ def func(self, other):
else:
other_codes = other._codes

f = getattr(self._codes, opname)
ret = f(other_codes)
ret = op(self._codes, other_codes)
mask = (self._codes == -1) | (other_codes == -1)
if mask.any():
# In other series, the leads to False, so do that here too
if opname == "__ne__":
ret[(self._codes == -1) & (other_codes == -1)] = True
else:
ret[mask] = False
ret[mask] = fill_value
Comment on lines 102 to +104
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it make sense to simplify further to only ret[(self._codes == -1) | (other_codes == -1)] = fill_value (or remove the if mask.any())?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm OK with it either way; we use the if mask.any() check elsewhere

return ret

if is_scalar(other):
if other in self.categories:
i = self.categories.get_loc(other)
ret = getattr(self._codes, opname)(i)
ret = op(self._codes, i)

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