Skip to content

Commit 306fbf9

Browse files
authored
BUG: sort_index did not respect ignore_index when not sorting (#44065)
1 parent c556062 commit 306fbf9

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,7 @@ Indexing
501501
- Bug in :meth:`DataFrame.nlargest` and :meth:`Series.nlargest` where sorted result did not count indexes containing ``np.nan`` (:issue:`28984`)
502502
- Bug in indexing on a non-unique object-dtype :class:`Index` with an NA scalar (e.g. ``np.nan``) (:issue:`43711`)
503503
- 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`)
504+
- Bug in :meth:`DataFrame.sort_index` where ``ignore_index=True`` was not being respected when the index was already sorted (:issue:`43591`)
504505
- Bug in :meth:`Index.get_indexer_non_unique` when index contains multiple ``np.datetime64("NaT")`` and ``np.timedelta64("NaT")`` (:issue:`43869`)
505506
-
506507

pandas/core/generic.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -4633,10 +4633,17 @@ def sort_index(
46334633
)
46344634

46354635
if indexer is None:
4636+
if inplace:
4637+
result = self
4638+
else:
4639+
result = self.copy()
4640+
4641+
if ignore_index:
4642+
result.index = default_index(len(self))
46364643
if inplace:
46374644
return
46384645
else:
4639-
return self.copy()
4646+
return result
46404647

46414648
baxis = self._get_block_manager_axis(axis)
46424649
new_data = self._mgr.take(indexer, axis=baxis, verify=False)

pandas/tests/frame/methods/test_sort_index.py

+19
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
Index,
1010
IntervalIndex,
1111
MultiIndex,
12+
RangeIndex,
1213
Series,
1314
Timestamp,
1415
)
@@ -418,6 +419,24 @@ def test_sort_index_ignore_index(
418419
tm.assert_frame_equal(result_df, expected_df)
419420
tm.assert_frame_equal(df, DataFrame(original_dict, index=original_index))
420421

422+
@pytest.mark.parametrize("inplace", [True, False])
423+
@pytest.mark.parametrize("ignore_index", [True, False])
424+
def test_respect_ignore_index(self, inplace, ignore_index):
425+
# GH 43591
426+
df = DataFrame({"a": [1, 2, 3]}, index=RangeIndex(4, -1, -2))
427+
result = df.sort_index(
428+
ascending=False, ignore_index=ignore_index, inplace=inplace
429+
)
430+
431+
if inplace:
432+
result = df
433+
if ignore_index:
434+
expected = DataFrame({"a": [1, 2, 3]})
435+
else:
436+
expected = DataFrame({"a": [1, 2, 3]}, index=RangeIndex(4, -1, -2))
437+
438+
tm.assert_frame_equal(result, expected)
439+
421440
@pytest.mark.parametrize("inplace", [True, False])
422441
@pytest.mark.parametrize(
423442
"original_dict, sorted_dict, ascending, ignore_index, output_index",

0 commit comments

Comments
 (0)