Skip to content

BUG: set_levels not preserving categorical #52177

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ Missing

MultiIndex
^^^^^^^^^^
-
- Bug in :meth:`MultiIndex.set_levels` not preserving dtypes for :class:`Categorical` (:issue:`52125`)
-

I/O
Expand Down
7 changes: 6 additions & 1 deletion pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
ABCDatetimeIndex,
ABCTimedeltaIndex,
)
from pandas.core.dtypes.inference import is_array_like
from pandas.core.dtypes.missing import (
array_equivalent,
isna,
Expand Down Expand Up @@ -945,7 +946,11 @@ def set_levels(
FrozenList([['a', 'b', 'c'], [1, 2, 3, 4]])
"""

if is_list_like(levels) and not isinstance(levels, Index):
if isinstance(levels, Index):
pass
elif is_array_like(levels):
levels = Index(levels)
elif is_list_like(levels):
levels = list(levels)

level, levels = _require_listlike(level, levels, "Levels")
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/multi/test_get_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,3 +367,11 @@ def test_set_levels_pos_args_removal():

with pytest.raises(TypeError, match="positional arguments"):
idx.set_codes([[0, 1], [1, 0]], 0)


def test_set_levels_categorical_keep_dtype():
# GH#52125
midx = MultiIndex.from_arrays([[5, 6]])
result = midx.set_levels(levels=pd.Categorical([1, 2]), level=0)
expected = MultiIndex.from_arrays([pd.Categorical([1, 2])])
tm.assert_index_equal(result, expected)