Skip to content

Commit 0f70266

Browse files
phoflmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#39944: Fix regression for setitem not aligning rhs with boolean indexer
1 parent ab8b2f9 commit 0f70266

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

doc/source/whatsnew/v1.2.3.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717

1818
- Fixed regression in :meth:`~DataFrame.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`)
19-
-
19+
- Fixed regression in :meth:`DataFrame.__setitem__` not aligning :class:`DataFrame` on right-hand side for boolean indexer (:issue:`39931`)
2020

2121
.. ---------------------------------------------------------------------------
2222

pandas/core/frame.py

+3
Original file line numberDiff line numberDiff line change
@@ -3179,6 +3179,9 @@ def _setitem_array(self, key, value):
31793179
key = check_bool_indexer(self.index, key)
31803180
indexer = key.nonzero()[0]
31813181
self._check_setitem_copy()
3182+
if isinstance(value, DataFrame):
3183+
# GH#39931 reindex since iloc does not align
3184+
value = value.reindex(self.index.take(indexer))
31823185
self.iloc[indexer] = value
31833186
else:
31843187
if isinstance(value, DataFrame):

pandas/tests/frame/indexing/test_setitem.py

+9
Original file line numberDiff line numberDiff line change
@@ -404,3 +404,12 @@ def test_setitem_boolean_mask(self, mask_type, float_frame):
404404
expected = df.copy()
405405
expected.values[np.array(mask)] = np.nan
406406
tm.assert_frame_equal(result, expected)
407+
408+
@pytest.mark.parametrize("indexer", [tm.setitem, tm.loc])
409+
def test_setitem_boolean_mask_aligning(self, indexer):
410+
# GH#39931
411+
df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]})
412+
expected = df.copy()
413+
mask = df["a"] >= 3
414+
indexer(df)[mask] = indexer(df)[mask].sort_values("a")
415+
tm.assert_frame_equal(df, expected)

0 commit comments

Comments
 (0)