Skip to content

Commit

Permalink
BUG: Fix sort_index(axis=1, ignore_index=True) (pandas-dev#56487)
Browse files Browse the repository at this point in the history
* BUG: Fix sort_index(axis=1, ignore_index=True)

* Switch condition
  • Loading branch information
mroeschke authored and cbpygit committed Jan 2, 2024
1 parent 7d310ba commit 5e2dff7
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -704,9 +704,10 @@ Other
- Bug in :func:`infer_freq` and :meth:`DatetimeIndex.inferred_freq` with weekly frequencies and non-nanosecond resolutions (:issue:`55609`)
- Bug in :meth:`DataFrame.apply` where passing ``raw=True`` ignored ``args`` passed to the applied function (:issue:`55009`)
- Bug in :meth:`DataFrame.from_dict` which would always sort the rows of the created :class:`DataFrame`. (:issue:`55683`)
- Bug in :meth:`DataFrame.sort_index` when passing ``axis="columns"`` and ``ignore_index=True`` raising a ``ValueError`` (:issue:`56478`)
- Bug in rendering ``inf`` values inside a a :class:`DataFrame` with the ``use_inf_as_na`` option enabled (:issue:`55483`)
- 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`)
- Bug in the error message when assigning an empty dataframe to a column (:issue:`55956`)
- Bug in the error message when assigning an empty :class:`DataFrame` to a column (:issue:`55956`)
- Bug when time-like strings were being cast to :class:`ArrowDtype` with ``pyarrow.time64`` type (:issue:`56463`)

.. ***DO NOT USE THIS SECTION***
Expand Down
10 changes: 5 additions & 5 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -5321,11 +5321,11 @@ def sort_index(
new_data = self._mgr.take(indexer, axis=baxis, verify=False)

# reconstruct axis if needed
new_data.set_axis(baxis, new_data.axes[baxis]._sort_levels_monotonic())

if ignore_index:
axis = 1 if isinstance(self, ABCDataFrame) else 0
new_data.set_axis(axis, default_index(len(indexer)))
if not ignore_index:
new_axis = new_data.axes[baxis]._sort_levels_monotonic()
else:
new_axis = default_index(len(indexer))
new_data.set_axis(baxis, new_axis)

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

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 @@ -994,3 +994,11 @@ def test_sort_index_with_sliced_multiindex():
),
)
tm.assert_frame_equal(result, expected)


def test_axis_columns_ignore_index():
# GH 56478
df = DataFrame([[1, 2]], columns=["d", "c"])
result = df.sort_index(axis="columns", ignore_index=True)
expected = DataFrame([[2, 1]])
tm.assert_frame_equal(result, expected)

0 comments on commit 5e2dff7

Please sign in to comment.