Skip to content

Commit 9ab4c45

Browse files
phoflyehoshuadimarsky
authored andcommitted
BUG: DataFrame.loc not aligning dict when setting to a column (pandas-dev#47361)
* BUG: DataFrame.loc not aligning dict when setting to a column * Add partial case * Use is_dict_like * Revert "Use is_dict_like" This reverts commit d270851.
1 parent 0de6f26 commit 9ab4c45

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

doc/source/whatsnew/v1.5.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -858,6 +858,7 @@ Indexing
858858
- Bug in :meth:`loc.__setitem__` treating ``range`` keys as positional instead of label-based (:issue:`45479`)
859859
- Bug in :meth:`Series.__setitem__` when setting ``boolean`` dtype values containing ``NA`` incorrectly raising instead of casting to ``boolean`` dtype (:issue:`45462`)
860860
- Bug in :meth:`Series.__setitem__` where setting :attr:`NA` into a numeric-dtype :class:`Series` would incorrectly upcast to object-dtype rather than treating the value as ``np.nan`` (:issue:`44199`)
861+
- Bug in :meth:`DataFrame.loc` when setting values to a column and right hand side is a dictionary (:issue:`47216`)
861862
- 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`)
862863
- Bug in :meth:`Index.__getitem__` raising ``ValueError`` when indexer is from boolean dtype with ``NA`` (:issue:`45806`)
863864
- 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

+2
Original file line numberDiff line numberDiff line change
@@ -4709,6 +4709,8 @@ def _sanitize_column(self, value) -> ArrayLike:
47094709
# We should never get here with DataFrame value
47104710
if isinstance(value, Series):
47114711
return _reindex_for_setitem(value, self.index)
4712+
elif isinstance(value, dict):
4713+
return _reindex_for_setitem(Series(value), self.index)
47124714

47134715
if is_list_like(value):
47144716
com.require_length_match(value, self.index)

pandas/tests/frame/indexing/test_setitem.py

+12
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,18 @@ def test_setitem_npmatrix_2d(self):
709709

710710
tm.assert_frame_equal(df, expected)
711711

712+
@pytest.mark.parametrize("vals", [{}, {"d": "a"}])
713+
def test_setitem_aligning_dict_with_index(self, vals):
714+
# GH#47216
715+
df = DataFrame({"a": [1, 2], "b": [3, 4], **vals})
716+
df.loc[:, "a"] = {1: 100, 0: 200}
717+
df.loc[:, "c"] = {0: 5, 1: 6}
718+
df.loc[:, "e"] = {1: 5}
719+
expected = DataFrame(
720+
{"a": [200, 100], "b": [3, 4], **vals, "c": [5, 6], "e": [np.nan, 5]}
721+
)
722+
tm.assert_frame_equal(df, expected)
723+
712724

713725
class TestSetitemTZAwareValues:
714726
@pytest.fixture

0 commit comments

Comments
 (0)