Skip to content

Backport PR #37787 on branch 1.1.x (Fix regression for loc and __setitem__ when one-dimensional tuple was given for MultiIndex) #37836

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

Closed
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.5.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- Regression in addition of a timedelta-like scalar to a :class:`DatetimeIndex` raising incorrectly (:issue:`37295`)
- Fixed regression in :meth:`Series.groupby` raising when the :class:`Index` of the :class:`Series` had a tuple as its name (:issue:`37755`)
- 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`)
-

.. ---------------------------------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,9 +641,9 @@ def _ensure_listlike_indexer(self, key, axis=None):
if self.ndim != 2:
return

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

Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/indexing/multiindex/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,23 @@ def convert_nested_indexer(indexer_type, keys):

tm.assert_series_equal(result, expected)

def test_multiindex_loc_one_dimensional_tuple(self, frame_or_series):
# GH#37711
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
obj = frame_or_series([1, 2], index=mi)
obj.loc[("a",)] = 0
expected = frame_or_series([0, 2], index=mi)
tm.assert_equal(obj, expected)

@pytest.mark.parametrize("indexer", [("a",), ("a")])
def test_multiindex_one_dimensional_tuple_columns(self, indexer):
# GH#37711
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
obj = DataFrame([1, 2], index=mi)
obj.loc[indexer, :] = 0
expected = DataFrame([0, 2], index=mi)
tm.assert_frame_equal(obj, expected)


@pytest.mark.parametrize(
"indexer, pos",
Expand Down