Skip to content

BUG: sort_index did not respect ignore_index when not sorting #44065

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 8 commits into from
Oct 19, 2021
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ Indexing
- Bug in :meth:`DataFrame.nlargest` and :meth:`Series.nlargest` where sorted result did not count indexes containing ``np.nan`` (:issue:`28984`)
- Bug in indexing on a non-unique object-dtype :class:`Index` with an NA scalar (e.g. ``np.nan``) (:issue:`43711`)
- Bug in :meth:`Series.__setitem__` with object dtype when setting an array with matching size and dtype='datetime64[ns]' or dtype='timedelta64[ns]' incorrectly converting the datetime/timedeltas to integers (:issue:`43868`)
-
- Bug in :meth:`DataFrame.sort_index` where ``ignore_index=True`` was not being respected when the index was already sorted (:issue:`43591`)

Missing
^^^^^^^
Expand Down
9 changes: 8 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4633,10 +4633,17 @@ def sort_index(
)

if indexer is None:
if inplace:
result = self
else:
result = self.copy()

if ignore_index:
result.index = default_index(len(self))
if inplace:
return
else:
return self.copy()
return result

baxis = self._get_block_manager_axis(axis)
new_data = self._mgr.take(indexer, axis=baxis, verify=False)
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/frame/methods/test_sort_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
Index,
IntervalIndex,
MultiIndex,
RangeIndex,
Series,
Timestamp,
)
Expand Down Expand Up @@ -418,6 +419,13 @@ def test_sort_index_ignore_index(
tm.assert_frame_equal(result_df, expected_df)
tm.assert_frame_equal(df, DataFrame(original_dict, index=original_index))

def test_respect_ignore_index(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you parameterize on inplace=True/False and ignore_index=True/False and check the cases

# GH 43591
df = DataFrame({"a": [1, 2, 3]}, index=RangeIndex(4, -1, -2))
result = df.sort_index(ascending=False, ignore_index=True)
expected = DataFrame({"a": [1, 2, 3]})
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("inplace", [True, False])
@pytest.mark.parametrize(
"original_dict, sorted_dict, ascending, ignore_index, output_index",
Expand Down