Skip to content

Commit b6834f8

Browse files
authored
PERF: Index.sort_values for already sorted index (#56128)
1 parent 86982eb commit b6834f8

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

doc/source/whatsnew/v2.2.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,7 @@ Performance improvements
417417
- Performance improvement in :meth:`DataFrame.loc` and :meth:`Series.loc` when indexing with a :class:`MultiIndex` (:issue:`56062`)
418418
- Performance improvement in :meth:`DataFrame.sort_index` and :meth:`Series.sort_index` when indexed by a :class:`MultiIndex` (:issue:`54835`)
419419
- Performance improvement in :meth:`Index.difference` (:issue:`55108`)
420+
- Performance improvement in :meth:`Index.sort_values` when index is already sorted (:issue:`56128`)
420421
- Performance improvement in :meth:`MultiIndex.get_indexer` when ``method`` is not ``None`` (:issue:`55839`)
421422
- Performance improvement in :meth:`Series.duplicated` for pyarrow dtypes (:issue:`55255`)
422423
- Performance improvement in :meth:`Series.str.get_dummies` when dtype is ``"string[pyarrow]"`` or ``"string[pyarrow_numpy]"`` (:issue:`56110`)

pandas/core/indexes/base.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5825,6 +5825,19 @@ def sort_values(
58255825
>>> idx.sort_values(ascending=False, return_indexer=True)
58265826
(Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))
58275827
"""
5828+
if key is None and (
5829+
self.is_monotonic_increasing or self.is_monotonic_decreasing
5830+
):
5831+
reverse = ascending != self.is_monotonic_increasing
5832+
sorted_index = self[::-1] if reverse else self.copy()
5833+
if return_indexer:
5834+
indexer = np.arange(len(self), dtype=np.intp)
5835+
if reverse:
5836+
indexer = indexer[::-1]
5837+
return sorted_index, indexer
5838+
else:
5839+
return sorted_index
5840+
58285841
# GH 35584. Sort missing values according to na_position kwarg
58295842
# ignore na_position for MultiIndex
58305843
if not isinstance(self, ABCMultiIndex):

0 commit comments

Comments
 (0)