Skip to content

Commit b80691c

Browse files
authored
Fix regression for loc and __setitem__ when one-dimensional tuple was given for MultiIndex (pandas-dev#37787)
1 parent 138d575 commit b80691c

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

doc/source/whatsnew/v1.1.5.rst

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717
- Regression in addition of a timedelta-like scalar to a :class:`DatetimeIndex` raising incorrectly (:issue:`37295`)
1818
- Fixed regression in :meth:`Series.groupby` raising when the :class:`Index` of the :class:`Series` had a tuple as its name (:issue:`37755`)
19+
- Fixed regression in :meth:`DataFrame.loc` and :meth:`Series.loc` for ``__setitem__`` when one-dimensional tuple was given to select from :class:`MultiIndex` (:issue:`37711`)
1920
-
2021

2122
.. ---------------------------------------------------------------------------

pandas/core/indexing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -650,9 +650,9 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None):
650650
if self.ndim != 2:
651651
return
652652

653-
if isinstance(key, tuple):
653+
if isinstance(key, tuple) and not isinstance(self.obj.index, ABCMultiIndex):
654654
# key may be a tuple if we are .loc
655-
# in that case, set key to the column part of key
655+
# if index is not a MultiIndex, set key to column part
656656
key = key[column_axis]
657657
axis = column_axis
658658

pandas/tests/indexing/multiindex/test_loc.py

+17
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,23 @@ def convert_nested_indexer(indexer_type, keys):
288288

289289
tm.assert_series_equal(result, expected)
290290

291+
def test_multiindex_loc_one_dimensional_tuple(self, frame_or_series):
292+
# GH#37711
293+
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
294+
obj = frame_or_series([1, 2], index=mi)
295+
obj.loc[("a",)] = 0
296+
expected = frame_or_series([0, 2], index=mi)
297+
tm.assert_equal(obj, expected)
298+
299+
@pytest.mark.parametrize("indexer", [("a",), ("a")])
300+
def test_multiindex_one_dimensional_tuple_columns(self, indexer):
301+
# GH#37711
302+
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
303+
obj = DataFrame([1, 2], index=mi)
304+
obj.loc[indexer, :] = 0
305+
expected = DataFrame([0, 2], index=mi)
306+
tm.assert_frame_equal(obj, expected)
307+
291308

292309
@pytest.mark.parametrize(
293310
"indexer, pos",

0 commit comments

Comments
 (0)