diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index 2762d84d73ba0..e50919175beb2 100755 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -43,6 +43,7 @@ API changes - Prettyprinting sets (e.g. in DataFrame cells) now uses set literal syntax (``{x, y}``) instead of Legacy Python syntax (``set([x, y])``) (:issue:`11215`) - Indexing with a null key will raise a ``TypeError``, instead of a ``ValueError`` (:issue:`11356`) +- Series.sort_index() now correctly handles ``inplace`` option (:issue:`11402`) .. _whatsnew_0171.deprecations: diff --git a/pandas/core/series.py b/pandas/core/series.py index 2fc90ef8596f1..b12a31d64eaf7 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1676,8 +1676,12 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False, ascending=ascending) new_values = self._values.take(indexer) - return self._constructor(new_values, - index=new_index).__finalize__(self) + result = self._constructor(new_values, index=new_index) + + if inplace: + self._update_inplace(result) + else: + return result.__finalize__(self) def sort(self, axis=0, ascending=True, kind='quicksort', na_position='last', inplace=True): """ diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py index 5ce25f5d93800..3b866e6965c2a 100644 --- a/pandas/tests/test_series.py +++ b/pandas/tests/test_series.py @@ -5328,6 +5328,30 @@ def test_sort_index(self): assert_series_equal(sorted_series, self.ts.reindex(self.ts.index[::-1])) + def test_sort_index_inplace(self): + + # For #11402 + rindex = list(self.ts.index) + random.shuffle(rindex) + + # descending + random_order = self.ts.reindex(rindex) + result = random_order.sort_index(ascending=False, inplace=True) + self.assertIs(result, None, + msg='sort_index() inplace should return None') + assert_index_equal(random_order.index, + self.ts.index[::-1]) + assert_series_equal(random_order, + self.ts.reindex(self.ts.index[::-1])) + + # ascending + random_order = self.ts.reindex(rindex) + result = random_order.sort_index(ascending=True, inplace=True) + self.assertIs(result, None, + msg='sort_index() inplace should return None') + assert_index_equal(random_order.index, self.ts.index) + assert_series_equal(random_order, self.ts) + def test_sort_API(self): # API for 9816