From 1f699c43f3e301eb7bd0af0d6a97512ffc890ee9 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Date: Tue, 11 Apr 2023 01:16:58 +0200 Subject: [PATCH] Backport PR #52565: REGR: Fix regression in sort_values not resetting index --- doc/source/whatsnew/v2.0.1.rst | 1 + pandas/core/frame.py | 8 ++++++-- pandas/tests/frame/methods/test_sort_values.py | 7 +++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v2.0.1.rst b/doc/source/whatsnew/v2.0.1.rst index 2b2a1029f6544..6174af17b24b0 100644 --- a/doc/source/whatsnew/v2.0.1.rst +++ b/doc/source/whatsnew/v2.0.1.rst @@ -15,6 +15,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression for subclassed Series when constructing from a dictionary (:issue:`52445`) - Fixed regression in :meth:`Series.describe` showing ``RuntimeWarning`` for extension dtype :class:`Series` with one element (:issue:`52515`) +- Fixed regression in :meth:`DataFrame.sort_values` not resetting index when :class:`DataFrame` is already sorted and ``ignore_index=True`` (:issue:`52553`) .. --------------------------------------------------------------------------- .. _whatsnew_201.bug_fixes: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1ecf5f4ee29dd..e6fc1ca71b174 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6784,10 +6784,14 @@ def sort_values( return self.copy(deep=None) if is_range_indexer(indexer, len(indexer)): + result = self.copy(deep=(not inplace and not using_copy_on_write())) + if ignore_index: + result.index = default_index(len(result)) + if inplace: - return self._update_inplace(self) + return self._update_inplace(result) else: - return self.copy(deep=None) + return result new_data = self._mgr.take( indexer, axis=self._get_block_manager_axis(axis), verify=False diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index 9092f30e0e4d0..e2877acbdd040 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -630,6 +630,13 @@ def test_sort_values_no_by_inplace(self): tm.assert_frame_equal(df, expected) assert result is None + def test_sort_values_no_op_reset_index(self): + # GH#52553 + df = DataFrame({"A": [10, 20], "B": [1, 5]}, index=[2, 3]) + result = df.sort_values(by="A", ignore_index=True) + expected = DataFrame({"A": [10, 20], "B": [1, 5]}) + tm.assert_frame_equal(result, expected) + class TestDataFrameSortKey: # test key sorting (issue 27237) def test_sort_values_inplace_key(self, sort_by_key):