Skip to content

Commit 77681d6

Browse files
authored
Backport PR #37787 on branch 1.1.x (Fix regression for loc and __setitem__ when one-dimensional tuple was given for MultiIndex) (#37849)
1 parent 7468864 commit 77681d6

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-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
@@ -641,9 +641,9 @@ def _ensure_listlike_indexer(self, key, axis=None):
641641
if self.ndim != 2:
642642
return
643643

644-
if isinstance(key, tuple):
644+
if isinstance(key, tuple) and not isinstance(self.obj.index, ABCMultiIndex):
645645
# key may be a tuple if we are .loc
646-
# in that case, set key to the column part of key
646+
# if index is not a MultiIndex, set key to column part
647647
key = key[column_axis]
648648
axis = column_axis
649649

pandas/tests/indexing/multiindex/test_loc.py

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

289289
tm.assert_series_equal(result, expected)
290290

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

292310
@pytest.mark.parametrize(
293311
"indexer, pos",

0 commit comments

Comments
 (0)