diff --git a/doc/source/whatsnew/v1.6.0.rst b/doc/source/whatsnew/v1.6.0.rst index d726f69286469..b29cf0424a9e7 100644 --- a/doc/source/whatsnew/v1.6.0.rst +++ b/doc/source/whatsnew/v1.6.0.rst @@ -148,7 +148,7 @@ Performance improvements - Performance improvement for :meth:`MultiIndex.intersection` (:issue:`48604`) - Performance improvement in ``var`` for nullable dtypes (:issue:`48379`). - Performance improvement to :func:`read_sas` with ``blank_missing=True`` (:issue:`48502`) -- +- Memory improvement in :meth:`RangeIndex.sort_values` (:issue:`48801`) .. --------------------------------------------------------------------------- .. _whatsnew_160.bug_fixes: diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 27b62776c3001..0948c5a3825d0 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -554,8 +554,6 @@ def sort_values( na_position: str = "last", key: Callable | None = None, ): - sorted_index = self - indexer = RangeIndex(range(len(self))) if key is not None: return super().sort_values( return_indexer=return_indexer, @@ -565,17 +563,22 @@ def sort_values( ) else: sorted_index = self + inverse_indexer = False if ascending: if self.step < 0: sorted_index = self[::-1] - indexer = indexer[::-1] + inverse_indexer = True else: if self.step > 0: sorted_index = self[::-1] - indexer = indexer = indexer[::-1] + inverse_indexer = True if return_indexer: - return sorted_index, indexer + if inverse_indexer: + rng = range(len(self) - 1, -1, -1) + else: + rng = range(len(self)) + return sorted_index, RangeIndex(rng) else: return sorted_index