diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 2c39318fa28b3..503da28684d60 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -241,9 +241,9 @@ Styler Other ^^^^^ +- Bug in :meth:`DataFrame.sort_index` when passing ``axis="columns"`` and ``ignore_index=True`` and ``ascending=False`` not returning a :class:`RangeIndex` columns (:issue:`57293`) - Bug in :meth:`DataFrame.where` where using a non-bool type array in the function would return a ``ValueError`` instead of a ``TypeError`` (:issue:`56330`) - .. ***DO NOT USE THIS SECTION*** - diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 93c2afab51d2c..1741c61e7195f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5080,7 +5080,10 @@ def sort_index( result = self.copy(deep=None) if ignore_index: - result.index = default_index(len(self)) + if axis == 1: + result.columns = default_index(len(self.columns)) + else: + result.index = default_index(len(self)) if inplace: return None else: diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 1a5df0778ec52..d88daaff685aa 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -1003,6 +1003,23 @@ def test_axis_columns_ignore_index(): tm.assert_frame_equal(result, expected) +def test_axis_columns_ignore_index_ascending_false(): + # GH 57293 + df = DataFrame( + { + "b": [1.0, 3.0, np.nan], + "a": [1, 4, 3], + 1: ["a", "b", "c"], + "e": [3, 1, 4], + "d": [1, 2, 8], + } + ).set_index(["b", "a", 1]) + result = df.sort_index(axis="columns", ignore_index=True, ascending=False) + expected = df.copy() + expected.columns = RangeIndex(2) + tm.assert_frame_equal(result, expected) + + def test_sort_index_stable_sort(): # GH 57151 df = DataFrame(