Skip to content

Commit 0ea10ff

Browse files
authored
Backport PR #47581 on branch 1.4.x (BUG: DataFrame.loc not aligning rhs df for single block case) (#47984)
1 parent 4c887ad commit 0ea10ff

File tree

4 files changed

+19
-2
lines changed

4 files changed

+19
-2
lines changed

doc/source/whatsnew/v1.4.4.rst

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717
- Fixed regression in :func:`concat` materializing :class:`Index` during sorting even if :class:`Index` was already sorted (:issue:`47501`)
1818
- Fixed regression in :meth:`DataFrame.loc` not updating the cache correctly after values were set (:issue:`47867`)
19+
- Fixed regression in :meth:`DataFrame.loc` not aligning index in some cases when setting a :class:`DataFrame` (:issue:`47578`)
1920
- Fixed regression in setting ``None`` or non-string value into a ``string``-dtype Series using a mask (:issue:`47628`)
2021
-
2122

pandas/core/frame.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -4527,8 +4527,8 @@ def _sanitize_column(self, value) -> ArrayLike:
45274527
"""
45284528
self._ensure_valid_index(value)
45294529

4530-
# We should never get here with DataFrame value
4531-
if isinstance(value, Series):
4530+
# We can get there through loc single_block_path
4531+
if isinstance(value, (DataFrame, Series)):
45324532
return _reindex_for_setitem(value, self.index)
45334533

45344534
if is_list_like(value):

pandas/tests/frame/indexing/test_indexing.py

+9
Original file line numberDiff line numberDiff line change
@@ -1323,6 +1323,15 @@ def test_loc_internals_not_updated_correctly(self):
13231323
)
13241324
tm.assert_series_equal(result, expected)
13251325

1326+
@pytest.mark.parametrize("val", ["x", 1])
1327+
@pytest.mark.parametrize("idxr", ["a", ["a"]])
1328+
def test_loc_setitem_rhs_frame(self, idxr, val):
1329+
# GH#47578
1330+
df = DataFrame({"a": [1, 2]})
1331+
df.loc[:, "a"] = DataFrame({"a": [val, 11]}, index=[1, 2])
1332+
expected = DataFrame({"a": [np.nan, val]})
1333+
tm.assert_frame_equal(df, expected)
1334+
13261335

13271336
class TestDataFrameIndexingUInt64:
13281337
def test_setitem(self, uint64_frame):

pandas/tests/frame/indexing/test_setitem.py

+7
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,13 @@ def test_setitem_npmatrix_2d(self):
699699

700700
tm.assert_frame_equal(df, expected)
701701

702+
def test_setitem_rhs_dataframe(self):
703+
# GH#47578
704+
df = DataFrame({"a": [1, 2]})
705+
df["a"] = DataFrame({"a": [10, 11]}, index=[1, 2])
706+
expected = DataFrame({"a": [np.nan, 10]})
707+
tm.assert_frame_equal(df, expected)
708+
702709

703710
class TestSetitemTZAwareValues:
704711
@pytest.fixture

0 commit comments

Comments
 (0)