Skip to content

Commit 88b5591

Browse files
committed
BUG: DataFrame.loc not aligning dict when setting to a column
1 parent 696e9bd commit 88b5591

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

doc/source/whatsnew/v1.5.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -821,6 +821,7 @@ Indexing
821821
- Bug in :meth:`loc.__setitem__` treating ``range`` keys as positional instead of label-based (:issue:`45479`)
822822
- Bug in :meth:`Series.__setitem__` when setting ``boolean`` dtype values containing ``NA`` incorrectly raising instead of casting to ``boolean`` dtype (:issue:`45462`)
823823
- Bug in :meth:`Series.__setitem__` where setting :attr:`NA` into a numeric-dtpye :class:`Series` would incorrectly upcast to object-dtype rather than treating the value as ``np.nan`` (:issue:`44199`)
824+
- Bug in :meth:`DataFrame.loc` when setting values to a column and right hand side is a dictionary (:issue:`47216`)
824825
- Bug in :meth:`Series.__setitem__` with ``datetime64[ns]`` dtype, an all-``False`` boolean mask, and an incompatible value incorrectly casting to ``object`` instead of retaining ``datetime64[ns]`` dtype (:issue:`45967`)
825826
- Bug in :meth:`Index.__getitem__` raising ``ValueError`` when indexer is from boolean dtype with ``NA`` (:issue:`45806`)
826827
- Bug in :meth:`Series.mask` with ``inplace=True`` or setting values with a boolean mask with small integer dtypes incorrectly raising (:issue:`45750`)

pandas/core/frame.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4699,6 +4699,8 @@ def _sanitize_column(self, value) -> ArrayLike:
46994699
# We should never get here with DataFrame value
47004700
if isinstance(value, Series):
47014701
return _reindex_for_setitem(value, self.index)
4702+
elif isinstance(value, dict):
4703+
return _reindex_for_setitem(Series(value), self.index)
47024704

47034705
if is_list_like(value):
47044706
com.require_length_match(value, self.index)

pandas/tests/frame/indexing/test_setitem.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,6 +702,15 @@ def test_setitem_npmatrix_2d(self):
702702

703703
tm.assert_frame_equal(df, expected)
704704

705+
@pytest.mark.parametrize("vals", [{}, {"d": "a"}])
706+
def test_setitem_aligning_dict_with_index(self, vals):
707+
# GH#47216
708+
df = DataFrame({"a": [1, 2], "b": [3, 4], **vals})
709+
df.loc[:, "a"] = {1: 100, 0: 200}
710+
df.loc[:, "c"] = {0: 5, 1: 6}
711+
expected = DataFrame({"a": [200, 100], "b": [3, 4], **vals, "c": [5, 6]})
712+
tm.assert_frame_equal(df, expected)
713+
705714

706715
class TestSetitemTZAwareValues:
707716
@pytest.fixture

0 commit comments

Comments
 (0)