Skip to content

Commit 6d599cb

Browse files
Backport PR pandas-dev#39161: Fix regression in loc setitem raising KeyError when enlarging df with multiindex (pandas-dev#39187)
Co-authored-by: patrick <[email protected]>
1 parent fa2241d commit 6d599cb

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
@@ -660,9 +660,9 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None):
660660
if self.ndim != 2:
661661
return
662662

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

pandas/tests/indexing/multiindex/test_loc.py

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

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

309324
@pytest.mark.parametrize(
310325
"indexer, pos",

0 commit comments

Comments
 (0)