Skip to content

Commit 5e2dff7

Browse files
mroeschkecbpygit
authored andcommitted
BUG: Fix sort_index(axis=1, ignore_index=True) (pandas-dev#56487)
* BUG: Fix sort_index(axis=1, ignore_index=True) * Switch condition
1 parent 7d310ba commit 5e2dff7

File tree

3 files changed

+15
-6
lines changed

3 files changed

+15
-6
lines changed

doc/source/whatsnew/v2.2.0.rst

+2-1
Original file line numberDiff line numberDiff line change
@@ -704,9 +704,10 @@ Other
704704
- Bug in :func:`infer_freq` and :meth:`DatetimeIndex.inferred_freq` with weekly frequencies and non-nanosecond resolutions (:issue:`55609`)
705705
- Bug in :meth:`DataFrame.apply` where passing ``raw=True`` ignored ``args`` passed to the applied function (:issue:`55009`)
706706
- Bug in :meth:`DataFrame.from_dict` which would always sort the rows of the created :class:`DataFrame`. (:issue:`55683`)
707+
- Bug in :meth:`DataFrame.sort_index` when passing ``axis="columns"`` and ``ignore_index=True`` raising a ``ValueError`` (:issue:`56478`)
707708
- Bug in rendering ``inf`` values inside a a :class:`DataFrame` with the ``use_inf_as_na`` option enabled (:issue:`55483`)
708709
- Bug in rendering a :class:`Series` with a :class:`MultiIndex` when one of the index level's names is 0 not having that name displayed (:issue:`55415`)
709-
- Bug in the error message when assigning an empty dataframe to a column (:issue:`55956`)
710+
- Bug in the error message when assigning an empty :class:`DataFrame` to a column (:issue:`55956`)
710711
- Bug when time-like strings were being cast to :class:`ArrowDtype` with ``pyarrow.time64`` type (:issue:`56463`)
711712

712713
.. ***DO NOT USE THIS SECTION***

pandas/core/generic.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -5321,11 +5321,11 @@ def sort_index(
53215321
new_data = self._mgr.take(indexer, axis=baxis, verify=False)
53225322

53235323
# reconstruct axis if needed
5324-
new_data.set_axis(baxis, new_data.axes[baxis]._sort_levels_monotonic())
5325-
5326-
if ignore_index:
5327-
axis = 1 if isinstance(self, ABCDataFrame) else 0
5328-
new_data.set_axis(axis, default_index(len(indexer)))
5324+
if not ignore_index:
5325+
new_axis = new_data.axes[baxis]._sort_levels_monotonic()
5326+
else:
5327+
new_axis = default_index(len(indexer))
5328+
new_data.set_axis(baxis, new_axis)
53295329

53305330
result = self._constructor_from_mgr(new_data, axes=new_data.axes)
53315331

pandas/tests/frame/methods/test_sort_index.py

+8
Original file line numberDiff line numberDiff line change
@@ -994,3 +994,11 @@ def test_sort_index_with_sliced_multiindex():
994994
),
995995
)
996996
tm.assert_frame_equal(result, expected)
997+
998+
999+
def test_axis_columns_ignore_index():
1000+
# GH 56478
1001+
df = DataFrame([[1, 2]], columns=["d", "c"])
1002+
result = df.sort_index(axis="columns", ignore_index=True)
1003+
expected = DataFrame([[2, 1]])
1004+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)