Skip to content

PERF: Faster comparisons of indexes when compared to self #37109

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

Closed
Closed
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: 18 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5363,6 +5363,24 @@ def _cmp_method(self, other, op):
"""
Wrapper used to dispatch comparison operations.
"""
from .multi import MultiIndex

if self.is_(other) and not isinstance(self, MultiIndex):
# short-circuit when other is same as self
# if we're comparing equality, return an np.ones array, else an np.zeros arr
bool_arr_type, na_bool = {
Copy link
Member

Choose a reason for hiding this comment

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

the pattern we use elsewhere is more like

res = np.empty(self.shape, dtype=bool)
res[:] = (op.__name__ in ["eq", "le", "ge"]
if self._can_hold_na:
   ...

operator.eq: (np.ones, False),
operator.le: (np.ones, False),
operator.ge: (np.ones, False),
operator.ne: (np.zeros, True),
operator.lt: (np.zeros, True),
operator.gt: (np.zeros, True),
}[op]
bool_arr = bool_arr_type(self.shape, dtype=bool)
if self._can_hold_na:
bool_arr[isna(self)] = na_bool
return bool_arr

if isinstance(other, (np.ndarray, Index, ABCSeries, ExtensionArray)):
if len(self) != len(other):
raise ValueError("Lengths must match to compare")
Expand Down