Skip to content

Commit ed21210

Browse files
authored
PERF: RangeIndex.insert (#43988)
1 parent 3d7cc02 commit ed21210

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

pandas/core/indexes/range.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -713,6 +713,20 @@ def symmetric_difference(self, other, result_name: Hashable = None, sort=None):
713713

714714
# --------------------------------------------------------------------
715715

716+
def insert(self, loc: int, item) -> Index:
717+
if len(self) and (is_integer(item) or is_float(item)):
718+
# We can retain RangeIndex is inserting at the beginning or end
719+
rng = self._range
720+
if loc == 0 and item == self[0] - self.step:
721+
new_rng = range(rng.start - rng.step, rng.stop, rng.step)
722+
return type(self)._simple_new(new_rng, name=self.name)
723+
724+
elif loc == len(self) and item == self[-1] + self.step:
725+
new_rng = range(rng.start, rng.stop + rng.step, rng.step)
726+
return type(self)._simple_new(new_rng, name=self.name)
727+
728+
return super().insert(loc, item)
729+
716730
def _concat(self, indexes: list[Index], name: Hashable) -> Index:
717731
"""
718732
Overriding parent method for the case of all RangeIndex instances.

pandas/tests/indexes/common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -821,7 +821,7 @@ def test_insert_non_na(self, simple_index):
821821
cls = Int64Index
822822

823823
expected = cls([index[0]] + list(index), dtype=index.dtype)
824-
tm.assert_index_equal(result, expected)
824+
tm.assert_index_equal(result, expected, exact=True)
825825

826826
def test_insert_na(self, nulls_fixture, simple_index):
827827
# GH 18295 (test missing)

0 commit comments

Comments
 (0)