Skip to content

Commit

Permalink
Backport PR #39944 on branch 1.2.x (Fix regression for setitem not al…
Browse files Browse the repository at this point in the history
…igning rhs with boolean indexer) (#39979)

Co-authored-by: patrick <61934744+phofl@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and phofl committed Feb 23, 2021
1 parent 30ddd5f commit 1325351
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.2.3.rst
Expand Up @@ -16,7 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~

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

.. ---------------------------------------------------------------------------
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/frame.py
Expand Up @@ -3179,6 +3179,9 @@ def _setitem_array(self, key, value):
key = check_bool_indexer(self.index, key)
indexer = key.nonzero()[0]
self._check_setitem_copy()
if isinstance(value, DataFrame):
# GH#39931 reindex since iloc does not align
value = value.reindex(self.index.take(indexer))
self.iloc[indexer] = value
else:
if isinstance(value, DataFrame):
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/frame/indexing/test_setitem.py
Expand Up @@ -404,3 +404,12 @@ def test_setitem_boolean_mask(self, mask_type, float_frame):
expected = df.copy()
expected.values[np.array(mask)] = np.nan
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("indexer", [lambda x: x, lambda x: x.loc])
def test_setitem_boolean_mask_aligning(self, indexer):
# GH#39931
df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]})
expected = df.copy()
mask = df["a"] >= 3
indexer(df)[mask] = indexer(df)[mask].sort_values("a")
tm.assert_frame_equal(df, expected)

0 comments on commit 1325351

Please sign in to comment.