Skip to content

Commit 2b82b86

Browse files
authored
PERF: Add short circuiting to RangeIndex._shallow_copy (#57534)
1 parent 1625d5a commit 2b82b86

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

pandas/core/indexes/range.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
index as libindex,
2323
lib,
2424
)
25-
from pandas._libs.algos import unique_deltas
2625
from pandas._libs.lib import no_default
2726
from pandas.compat.numpy import function as nv
2827
from pandas.util._decorators import (
@@ -469,15 +468,18 @@ def _shallow_copy(self, values, name: Hashable = no_default):
469468

470469
if values.dtype.kind == "f":
471470
return Index(values, name=name, dtype=np.float64)
472-
# GH 46675 & 43885: If values is equally spaced, return a
473-
# more memory-compact RangeIndex instead of Index with 64-bit dtype
474-
unique_diffs = unique_deltas(values)
475-
if len(unique_diffs) == 1 and unique_diffs[0] != 0:
476-
diff = unique_diffs[0]
477-
new_range = range(values[0], values[-1] + diff, diff)
478-
return type(self)._simple_new(new_range, name=name)
479-
else:
480-
return self._constructor._simple_new(values, name=name)
471+
if values.dtype.kind == "i" and values.ndim == 1 and len(values) > 1:
472+
# GH 46675 & 43885: If values is equally spaced, return a
473+
# more memory-compact RangeIndex instead of Index with 64-bit dtype
474+
diff = values[1] - values[0]
475+
if diff != 0:
476+
maybe_range_indexer, remainder = np.divmod(values - values[0], diff)
477+
if (remainder == 0).all() and lib.is_range_indexer(
478+
maybe_range_indexer, len(maybe_range_indexer)
479+
):
480+
new_range = range(values[0], values[-1] + diff, diff)
481+
return type(self)._simple_new(new_range, name=name)
482+
return self._constructor._simple_new(values, name=name)
481483

482484
def _view(self) -> Self:
483485
result = type(self)._simple_new(self._range, name=self._name)

0 commit comments

Comments
 (0)