Skip to content

Commit

Permalink
BUG: Fix sort_index(axis=1, ignore_index=True)
Browse files Browse the repository at this point in the history
  • Loading branch information
mroeschke committed Dec 13, 2023
1 parent db6fd22 commit d7f64be
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 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 @@ -694,9 +694,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`)
-

.. ***DO NOT USE THIS SECTION***
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -5352,11 +5352,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)))
new_axis = default_index(len(indexer))
else:
new_axis = new_data.axes[baxis]._sort_levels_monotonic()
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 d7f64be

Please sign in to comment.