Skip to content

Commit 654b11e

Browse files
mroeschkepmhatre1
authored andcommitted
PERF: RangeIndex.append returns a RangeIndex when possible (pandas-dev#57467)
* PERF: RangeIndex.append returns a RangeIndex when possible * add correct issue number * add correct issue number * Only if int * Guard on integer dtype kind * Add test for return Index case
1 parent b3dd3d5 commit 654b11e

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,7 @@ Removal of prior version deprecations/changes
245245

246246
Performance improvements
247247
~~~~~~~~~~~~~~~~~~~~~~~~
248+
- :meth:`RangeIndex.append` returns a :class:`RangeIndex` instead of a :class:`Index` when appending values that could continue the :class:`RangeIndex` (:issue:`57467`)
248249
- :meth:`Series.str.extract` returns a :class:`RangeIndex` columns instead of an :class:`Index` column when possible (:issue:`57542`)
249250
- Performance improvement in :class:`DataFrame` when ``data`` is a ``dict`` and ``columns`` is specified (:issue:`24368`)
250251
- Performance improvement in :meth:`DataFrame.join` for sorted but non-unique indexes (:issue:`56941`)

pandas/core/indexes/range.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -989,7 +989,10 @@ def _concat(self, indexes: list[Index], name: Hashable) -> Index:
989989
indexes = [RangeIndex(3), RangeIndex(4, 6)] -> Index([0,1,2,4,5], dtype='int64')
990990
"""
991991
if not all(isinstance(x, RangeIndex) for x in indexes):
992-
return super()._concat(indexes, name)
992+
result = super()._concat(indexes, name)
993+
if result.dtype.kind == "i":
994+
return self._shallow_copy(result._values)
995+
return result
993996

994997
elif len(indexes) == 1:
995998
return indexes[0]

pandas/tests/indexes/ranges/test_range.py

+14
Original file line numberDiff line numberDiff line change
@@ -608,6 +608,20 @@ def test_range_index_rsub_by_const(self):
608608
tm.assert_index_equal(result, expected)
609609

610610

611+
def test_append_non_rangeindex_return_rangeindex():
612+
ri = RangeIndex(1)
613+
result = ri.append(Index([1]))
614+
expected = RangeIndex(2)
615+
tm.assert_index_equal(result, expected, exact=True)
616+
617+
618+
def test_append_non_rangeindex_return_index():
619+
ri = RangeIndex(1)
620+
result = ri.append(Index([1, 3, 4]))
621+
expected = Index([0, 1, 3, 4])
622+
tm.assert_index_equal(result, expected, exact=True)
623+
624+
611625
def test_reindex_returns_rangeindex():
612626
ri = RangeIndex(2, name="foo")
613627
result, result_indexer = ri.reindex([1, 2, 3])

0 commit comments

Comments
 (0)