Skip to content

Commit 49778b0

Browse files
authored
Fix regression in loc setitem raising KeyError when enlarging df with multiindex (#39161)
1 parent 0b62e86 commit 49778b0

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

doc/source/whatsnew/v1.2.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ Fixed regressions
2929
- Fixed regression in :meth:`DataFrameGroupBy.diff` raising for ``int8`` and ``int16`` columns (:issue:`39050`)
3030
- Fixed regression that raised ``AttributeError`` with PyArrow versions [0.16.0, 1.0.0) (:issue:`38801`)
3131
- Fixed regression in :meth:`DataFrame.groupby` when aggregating an :class:`ExtensionDType` that could fail for non-numeric values (:issue:`38980`)
32-
-
32+
- Fixed regression in :meth:`DataFrame.loc.__setitem__` raising ``KeyError`` with :class:`MultiIndex` and list-like columns indexer enlarging :class:`DataFrame` (:issue:`39147`)
3333
-
3434

3535
.. ---------------------------------------------------------------------------

pandas/core/indexing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -663,9 +663,9 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None):
663663
if self.ndim != 2:
664664
return
665665

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

pandas/tests/indexing/multiindex/test_loc.py

+15
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,21 @@ def test_multiindex_one_dimensional_tuple_columns(self, indexer):
308308
expected = DataFrame([0, 2], index=mi)
309309
tm.assert_frame_equal(obj, expected)
310310

311+
@pytest.mark.parametrize(
312+
"indexer, exp_value", [(slice(None), 1.0), ((1, 2), np.nan)]
313+
)
314+
def test_multiindex_setitem_columns_enlarging(self, indexer, exp_value):
315+
# GH#39147
316+
mi = MultiIndex.from_tuples([(1, 2), (3, 4)])
317+
df = DataFrame([[1, 2], [3, 4]], index=mi, columns=["a", "b"])
318+
df.loc[indexer, ["c", "d"]] = 1.0
319+
expected = DataFrame(
320+
[[1, 2, 1.0, 1.0], [3, 4, exp_value, exp_value]],
321+
index=mi,
322+
columns=["a", "b", "c", "d"],
323+
)
324+
tm.assert_frame_equal(df, expected)
325+
311326

312327
@pytest.mark.parametrize(
313328
"indexer, pos",

0 commit comments

Comments
 (0)