From b40c1ab3c44f211532c166327e02c44bf8ce23e6 Mon Sep 17 00:00:00 2001 From: Younggun Kim Date: Mon, 12 Oct 2015 17:00:37 +0900 Subject: [PATCH] PERF: Checking monotonic-ness before sorting on an index #11080 --- asv_bench/benchmarks/frame_methods.py | 10 ++++++++++ doc/source/whatsnew/v0.17.1.txt | 2 ++ pandas/core/frame.py | 9 +++++++++ 3 files changed, 21 insertions(+) diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 9bece56e15c90..a04a9d0814a30 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -930,6 +930,16 @@ def time_frame_xs_row(self): self.df.xs(50000) +class frame_sort_index(object): + goal_time = 0.2 + + def setup(self): + self.df = DataFrame(randn(1000000, 2), columns=list('AB')) + + def time_frame_sort_index(self): + self.df.sort_index() + + class series_string_vector_slice(object): goal_time = 0.2 diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index 507c829e5763f..945840184a00c 100755 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -52,6 +52,8 @@ Deprecations Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ +- Checking monotonic-ness before sorting on an index (:issue:`11080`) + .. _whatsnew_0171.bug_fixes: Bug Fixes diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 920d9ad96c5b6..e92de770ac4bd 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3157,6 +3157,15 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False, else: from pandas.core.groupby import _nargsort + # GH11080 - Check monotonic-ness before sort an index + # if monotonic (already sorted), return None or copy() according to 'inplace' + if (ascending and labels.is_monotonic_increasing) or \ + (not ascending and labels.is_monotonic_decreasing): + if inplace: + return + else: + return self.copy() + indexer = _nargsort(labels, kind=kind, ascending=ascending, na_position=na_position)