Skip to content

Commit 194b6bb

Browse files
m-richardsjorisvandenbosschemroeschke
authored
BUG: Fix getitem dtype preservation with multiindexes (#51895)
* BUG/TST fix dtype preservation with multindex * lint * Update pandas/tests/indexing/multiindex/test_multiindex.py Co-authored-by: Joris Van den Bossche <[email protected]> * cleanups * switch to iloc, reindex fails in some cases * suggestions from code review * address code review comments Co-Authored-By: Matthew Roeschke <[email protected]> --------- Co-authored-by: Joris Van den Bossche <[email protected]> Co-authored-by: Matthew Roeschke <[email protected]>
1 parent 61738c4 commit 194b6bb

File tree

3 files changed

+23
-13
lines changed

3 files changed

+23
-13
lines changed

Diff for: doc/source/whatsnew/v2.1.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -350,8 +350,8 @@ Missing
350350

351351
MultiIndex
352352
^^^^^^^^^^
353+
- Bug in :meth:`DataFrame.__getitem__` not preserving dtypes for :class:`MultiIndex` partial keys (:issue:`51895`)
353354
- Bug in :meth:`MultiIndex.set_levels` not preserving dtypes for :class:`Categorical` (:issue:`52125`)
354-
-
355355

356356
I/O
357357
^^^

Diff for: pandas/core/frame.py

+2-12
Original file line numberDiff line numberDiff line change
@@ -3831,18 +3831,8 @@ def _getitem_multilevel(self, key):
38313831
if isinstance(loc, (slice, np.ndarray)):
38323832
new_columns = self.columns[loc]
38333833
result_columns = maybe_droplevels(new_columns, key)
3834-
if self._is_mixed_type:
3835-
result = self.reindex(columns=new_columns)
3836-
result.columns = result_columns
3837-
else:
3838-
new_values = self._values[:, loc]
3839-
result = self._constructor(
3840-
new_values, index=self.index, columns=result_columns, copy=False
3841-
)
3842-
if using_copy_on_write() and isinstance(loc, slice):
3843-
result._mgr.add_references(self._mgr) # type: ignore[arg-type]
3844-
3845-
result = result.__finalize__(self)
3834+
result = self.iloc[:, loc]
3835+
result.columns = result_columns
38463836

38473837
# If there is only one column being returned, and its name is
38483838
# either an empty string, or a tuple with an empty string as its

Diff for: pandas/tests/indexing/multiindex/test_multiindex.py

+20
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@
66

77
import pandas as pd
88
from pandas import (
9+
CategoricalDtype,
910
DataFrame,
1011
Index,
1112
MultiIndex,
1213
Series,
1314
)
1415
import pandas._testing as tm
16+
from pandas.core.arrays.boolean import BooleanDtype
1517

1618

1719
class TestMultiIndexBasic:
@@ -207,6 +209,24 @@ def test_multiindex_with_na_missing_key(self):
207209
with pytest.raises(KeyError, match="missing_key"):
208210
df[[("missing_key",)]]
209211

212+
def test_multiindex_dtype_preservation(self):
213+
# GH51261
214+
columns = MultiIndex.from_tuples([("A", "B")], names=["lvl1", "lvl2"])
215+
df = DataFrame(["value"], columns=columns).astype("category")
216+
df_no_multiindex = df["A"]
217+
assert isinstance(df_no_multiindex["B"].dtype, CategoricalDtype)
218+
219+
# geopandas 1763 analogue
220+
df = DataFrame(
221+
[[1, 0], [0, 1]],
222+
columns=[
223+
["foo", "foo"],
224+
["location", "location"],
225+
["x", "y"],
226+
],
227+
).assign(bools=Series([True, False], dtype="boolean"))
228+
assert isinstance(df["bools"].dtype, BooleanDtype)
229+
210230
def test_multiindex_from_tuples_with_nan(self):
211231
# GH#23578
212232
result = MultiIndex.from_tuples([("a", "b", "c"), np.nan, ("d", "", "")])

0 commit comments

Comments
 (0)