Skip to content

Commit 5f5350b

Browse files
authored
Bug in loc raising KeyError when MultiIndex columns has only one level (#38026)
* Bug in loc raising KeyError when MultiIndex columns has only one level * Move test * Revert commit
1 parent 1cc030e commit 5f5350b

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

doc/source/whatsnew/v1.2.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,7 @@ Indexing
621621
- Bug in :meth:`DataFrame.iloc` and :meth:`Series.iloc` aligning objects in ``__setitem__`` (:issue:`22046`)
622622
- Bug in :meth:`DataFrame.loc` did not raise ``KeyError`` when missing combination was given with ``slice(None)`` for remaining levels (:issue:`19556`)
623623
- Bug in :meth:`DataFrame.loc` raising ``TypeError`` when non-integer slice was given to select values from :class:`MultiIndex` (:issue:`25165`, :issue:`24263`)
624+
- Bug in :meth:`DataFrame.loc` and :meth:`DataFrame.__getitem__` raising ``KeyError`` when columns were :class:`MultiIndex` with only one level (:issue:`29749`)
624625

625626
Missing
626627
^^^^^^^

pandas/core/frame.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2935,7 +2935,7 @@ def __getitem__(self, key):
29352935
if is_hashable(key):
29362936
# shortcut if the key is in columns
29372937
if self.columns.is_unique and key in self.columns:
2938-
if self.columns.nlevels > 1:
2938+
if isinstance(self.columns, MultiIndex):
29392939
return self._getitem_multilevel(key)
29402940
return self._get_item_cache(key)
29412941

pandas/tests/frame/indexing/test_getitem.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,17 @@ def test_getitem_callable(self, float_frame):
9696
expected = float_frame.iloc[[0, 2], :]
9797
tm.assert_frame_equal(result, expected)
9898

99+
def test_loc_multiindex_columns_one_level(self):
100+
# GH#29749
101+
df = DataFrame([[1, 2]], columns=[["a", "b"]])
102+
expected = DataFrame([1], columns=[["a"]])
103+
104+
result = df["a"]
105+
tm.assert_frame_equal(result, expected)
106+
107+
result = df.loc[:, "a"]
108+
tm.assert_frame_equal(result, expected)
109+
99110

100111
class TestGetitemBooleanMask:
101112
def test_getitem_bool_mask_categorical_index(self):

0 commit comments

Comments
 (0)