Skip to content

Commit 11f11a0

Browse files
committed
BUG: implement Series.sort_index(..inplace=True) for pandas-dev#11402
1 parent 9a6de4e commit 11f11a0

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

doc/source/whatsnew/v0.17.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ API changes
4343
- Prettyprinting sets (e.g. in DataFrame cells) now uses set literal syntax (``{x, y}``) instead of
4444
Legacy Python syntax (``set([x, y])``) (:issue:`11215`)
4545
- Indexing with a null key will raise a ``TypeError``, instead of a ``ValueError`` (:issue:`11356`)
46+
- Series.sort_index() now correctly handles ``inplace`` option (:issue:`11402`)
4647

4748
.. _whatsnew_0171.deprecations:
4849

pandas/core/series.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -1676,8 +1676,12 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
16761676
ascending=ascending)
16771677

16781678
new_values = self._values.take(indexer)
1679-
return self._constructor(new_values,
1680-
index=new_index).__finalize__(self)
1679+
result = self._constructor(new_values, index=new_index)
1680+
1681+
if inplace:
1682+
self._update_inplace(result)
1683+
else:
1684+
return result.__finalize__(self)
16811685

16821686
def sort(self, axis=0, ascending=True, kind='quicksort', na_position='last', inplace=True):
16831687
"""

pandas/tests/test_series.py

+24
Original file line numberDiff line numberDiff line change
@@ -5328,6 +5328,30 @@ def test_sort_index(self):
53285328
assert_series_equal(sorted_series,
53295329
self.ts.reindex(self.ts.index[::-1]))
53305330

5331+
def test_sort_index_inplace(self):
5332+
5333+
# For #11402
5334+
rindex = list(self.ts.index)
5335+
random.shuffle(rindex)
5336+
5337+
# descending
5338+
random_order = self.ts.reindex(rindex)
5339+
result = random_order.sort_index(ascending=False, inplace=True)
5340+
self.assertIs(result, None,
5341+
msg='sort_index() inplace should return None')
5342+
assert_index_equal(random_order.index,
5343+
self.ts.index[::-1])
5344+
assert_series_equal(random_order,
5345+
self.ts.reindex(self.ts.index[::-1]))
5346+
5347+
# ascending
5348+
random_order = self.ts.reindex(rindex)
5349+
result = random_order.sort_index(ascending=True, inplace=True)
5350+
self.assertIs(result, None,
5351+
msg='sort_index() inplace should return None')
5352+
assert_index_equal(random_order.index, self.ts.index)
5353+
assert_series_equal(random_order, self.ts)
5354+
53315355
def test_sort_API(self):
53325356

53335357
# API for 9816

0 commit comments

Comments
 (0)