Skip to content

Commit 33dfa6c

Browse files
Backport PR #52565 on branch 2.0.x (REGR: Fix regression in sort_values not resetting index) (#52583)
Backport PR #52565: REGR: Fix regression in sort_values not resetting index Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com>
1 parent 04a87e5 commit 33dfa6c

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v2.0.1.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Fixed regressions
1515
~~~~~~~~~~~~~~~~~
1616
- Fixed regression for subclassed Series when constructing from a dictionary (:issue:`52445`)
1717
- Fixed regression in :meth:`Series.describe` showing ``RuntimeWarning`` for extension dtype :class:`Series` with one element (:issue:`52515`)
18+
- Fixed regression in :meth:`DataFrame.sort_values` not resetting index when :class:`DataFrame` is already sorted and ``ignore_index=True`` (:issue:`52553`)
1819

1920
.. ---------------------------------------------------------------------------
2021
.. _whatsnew_201.bug_fixes:

pandas/core/frame.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6784,10 +6784,14 @@ def sort_values(
67846784
return self.copy(deep=None)
67856785

67866786
if is_range_indexer(indexer, len(indexer)):
6787+
result = self.copy(deep=(not inplace and not using_copy_on_write()))
6788+
if ignore_index:
6789+
result.index = default_index(len(result))
6790+
67876791
if inplace:
6788-
return self._update_inplace(self)
6792+
return self._update_inplace(result)
67896793
else:
6790-
return self.copy(deep=None)
6794+
return result
67916795

67926796
new_data = self._mgr.take(
67936797
indexer, axis=self._get_block_manager_axis(axis), verify=False

pandas/tests/frame/methods/test_sort_values.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,13 @@ def test_sort_values_no_by_inplace(self):
630630
tm.assert_frame_equal(df, expected)
631631
assert result is None
632632

633+
def test_sort_values_no_op_reset_index(self):
634+
# GH#52553
635+
df = DataFrame({"A": [10, 20], "B": [1, 5]}, index=[2, 3])
636+
result = df.sort_values(by="A", ignore_index=True)
637+
expected = DataFrame({"A": [10, 20], "B": [1, 5]})
638+
tm.assert_frame_equal(result, expected)
639+
633640

634641
class TestDataFrameSortKey: # test key sorting (issue 27237)
635642
def test_sort_values_inplace_key(self, sort_by_key):

0 commit comments

Comments
 (0)