Skip to content

Backport PR #39161 on branch 1.2.x (Fix regression in loc setitem raising KeyError when enlarging df with multiindex) #39187

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
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.2.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Fixed regressions
- Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`)
- Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`)
- Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`)
-
- Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`)
-

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

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

Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/indexing/multiindex/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,21 @@ def test_multiindex_one_dimensional_tuple_columns(self, indexer):
expected = DataFrame([0, 2], index=mi)
tm.assert_frame_equal(obj, expected)

@pytest.mark.parametrize(
"indexer, exp_value", [(slice(None), 1.0), ((1, 2), np.nan)]
)
def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value):
# GH#39147
mi = MultiIndex.from_tuples([(1, 2), (3, 4)])
df = DataFrame([[1, 2], [3, 4]], index=mi, columns=["a", "b"])
df.loc[indexer, ["c", "d"]] = 1.0
expected = DataFrame(
[[1, 2, 1.0, 1.0], [3, 4, exp_value, exp_value]],
index=mi,
columns=["a", "b", "c", "d"],
)
tm.assert_frame_equal(df, expected)


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