Skip to content

Commit

Permalink
Backport PR #52565 on branch 2.0.x (REGR: Fix regression in sort_valu…
Browse files Browse the repository at this point in the history
…es 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>
  • Loading branch information
meeseeksmachine and phofl committed Apr 11, 2023
1 parent 04a87e5 commit 33dfa6c
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
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

0 comments on commit 33dfa6c

Please sign in to comment.