Skip to content

Backport PR #52565 on branch 2.0.x (REGR: Fix regression in sort_values not resetting index) #52583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 6 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/frame/methods/test_sort_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down