Skip to content

Commit 9bcc4ea

Browse files
committed
Make is_range
1 parent 9b18b6b commit 9bcc4ea

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed

pandas/_libs/lib.pyi

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,3 +231,7 @@ def is_range_indexer(
231231
left: np.ndarray,
232232
n: int, # np.ndarray[np.int64, ndim=1]
233233
) -> bool: ...
234+
def is_range(
235+
left: np.ndarray,
236+
diff: int, # np.ndarray[np.int64, ndim=1]
237+
) -> bool: ...

pandas/_libs/lib.pyx

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -659,20 +659,40 @@ ctypedef fused int6432_t:
659659

660660
@cython.wraparound(False)
661661
@cython.boundscheck(False)
662-
def is_range_indexer(ndarray[int6432_t, ndim=1] left, Py_ssize_t n, int diff=1) -> bool:
662+
def is_range_indexer(ndarray[int6432_t, ndim=1] left, Py_ssize_t n) -> bool:
663663
"""
664664
Perform an element by element comparison on 1-d integer arrays, meant for indexer
665665
comparisons
666666
"""
667667
cdef:
668668
Py_ssize_t i
669669

670-
if left.size != n or diff == 0:
670+
if left.size != n:
671671
return False
672672

673673
for i in range(n):
674674

675-
if left[i] != left[0] + i * diff:
675+
if left[i] != i:
676+
return False
677+
678+
return True
679+
680+
681+
@cython.wraparound(False)
682+
@cython.boundscheck(False)
683+
def is_range(ndarray[int6432_t, ndim=1] sequence, int64_t diff) -> bool:
684+
"""
685+
Check if sequence is equivalent to a range with the specified diff.
686+
"""
687+
cdef:
688+
Py_ssize_t i, n = len(sequence)
689+
690+
if diff == 0:
691+
return False
692+
693+
for i in range(n):
694+
695+
if sequence[i] != sequence[0] + i * diff:
676696
return False
677697

678698
return True

pandas/core/indexes/range.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -476,9 +476,7 @@ def _shallow_copy(self, values, name: Hashable = no_default):
476476
# GH 46675 & 43885: If values is equally spaced, return a
477477
# more memory-compact RangeIndex instead of Index with 64-bit dtype
478478
diff = values[1] - values[0]
479-
if not missing.isna(diff) and lib.is_range_indexer(
480-
values, len(values), diff
481-
):
479+
if not missing.isna(diff) and lib.is_range(values, diff):
482480
new_range = range(values[0], values[-1] + diff, diff)
483481
return type(self)._simple_new(new_range, name=name)
484482
return self._constructor._simple_new(values, name=name)

0 commit comments

Comments
 (0)