Skip to content

BUG: Fix getitem dtype preservation with multiindexes #51895

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 14 commits into from
Apr 25, 2023
Merged
Show file tree
Hide file tree
Changes from 13 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
14 changes: 2 additions & 12 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3831,18 +3831,8 @@ def _getitem_multilevel(self, key):
if isinstance(loc, (slice, np.ndarray)):
new_columns = self.columns[loc]
result_columns = maybe_droplevels(new_columns, key)
if self._is_mixed_type:
result = self.reindex(columns=new_columns)
result.columns = result_columns
else:
new_values = self._values[:, loc]
result = self._constructor(
new_values, index=self.index, columns=result_columns, copy=False
)
if using_copy_on_write() and isinstance(loc, slice):
result._mgr.add_references(self._mgr) # type: ignore[arg-type]

result = result.__finalize__(self)
result = self.iloc[:, loc]
result.columns = result_columns

# If there is only one column being returned, and its name is
# either an empty string, or a tuple with an empty string as its
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/indexing/multiindex/test_multiindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import pandas._libs.index as _index
from pandas.errors import PerformanceWarning

from pandas.core.dtypes.common import is_categorical_dtype

import pandas as pd
from pandas import (
DataFrame,
Expand All @@ -12,6 +14,7 @@
Series,
)
import pandas._testing as tm
from pandas.core.arrays.boolean import BooleanDtype


class TestMultiIndexBasic:
Expand Down Expand Up @@ -207,6 +210,24 @@ def test_multiindex_with_na_missing_key(self):
with pytest.raises(KeyError, match="missing_key"):
df[[("missing_key",)]]

def test_multiindex_dtype_preservation(self):
# GH51261
columns = MultiIndex.from_tuples([("A", "B")], names=["lvl1", "lvl2"])
df = DataFrame(["value"], columns=columns).astype("category")
df_no_multiindex = df["A"]
assert is_categorical_dtype(df_no_multiindex["B"])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
assert is_categorical_dtype(df_no_multiindex["B"])
assert isinstance(df_no_multiindex["B"].dtype, CategoricalDtype)

CategoricalDtype will need an import at the top


# geopandas 1763 analogue
df = DataFrame(
[[1, 0], [0, 1]],
columns=[
["foo", "foo"],
["location", "location"],
["x", "y"],
],
).assign(bools=Series([True, False], dtype="boolean"))
assert isinstance(df["bools"].dtype, BooleanDtype)

def test_multiindex_from_tuples_with_nan(self):
# GH#23578
result = MultiIndex.from_tuples([("a", "b", "c"), np.nan, ("d", "", "")])
Expand Down