Skip to content

PERF: Delay creation of indexer in RangeIndex.sort_values #48801

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.6.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
13 changes: 8 additions & 5 deletions pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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

Expand Down