Skip to content

Fix regression for loc and __setitem__ when one-dimensional tuple was given for MultiIndex #37787

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

Merged
merged 8 commits into from
Nov 14, 2020
Merged
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,7 @@ Indexing
- Bug in :meth:`Index.where` incorrectly casting numeric values to strings (:issue:`37591`)
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` raises when numeric label was given for object :class:`Index` although label was in :class:`Index` (:issue:`26491`)
- Bug in :meth:`DataFrame.loc` returned requested key plus missing values when ``loc`` was applied to single level from :class:`MultiIndex` (:issue:`27104`)
- 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`)

Missing
^^^^^^^
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,11 +650,12 @@ def _ensure_listlike_indexer(self, key, axis=None, value=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
pass

if (
axis == column_axis
Expand Down
14 changes: 14 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,20 @@ def convert_nested_indexer(indexer_type, keys):

tm.assert_series_equal(result, expected)

def test_multiindex_loc_one_dimensional_tuple(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use frame_or_series

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

# GH#37711
mi = MultiIndex.from_tuples([("a", "A"), ("b", "A")])
ser = Series([1, 2], index=mi)
df = ser.to_frame()

ser.loc[("a",)] = 0
expected = Series([0, 2], index=mi)
tm.assert_series_equal(ser, expected)

df.loc[("a",)] = 0
expected = expected.to_frame()
tm.assert_frame_equal(df, expected)


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