Skip to content

Commit c3012b1

Browse files
authored
BUG: DataFrame.__setitem__ raising ValueError when setting multiple values to dup columns (#39280)
1 parent 0270b23 commit c3012b1

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,7 @@ Indexing
279279
^^^^^^^^
280280
- Bug in :meth:`CategoricalIndex.get_indexer` failing to raise ``InvalidIndexError`` when non-unique (:issue:`38372`)
281281
- Bug in inserting many new columns into a :class:`DataFrame` causing incorrect subsequent indexing behavior (:issue:`38380`)
282+
- Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` when setting multiple values to duplicate columns (:issue:`15695`)
282283
- Bug in :meth:`DataFrame.loc`, :meth:`Series.loc`, :meth:`DataFrame.__getitem__` and :meth:`Series.__getitem__` returning incorrect elements for non-monotonic :class:`DatetimeIndex` for string slices (:issue:`33146`)
283284
- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` with timezone aware indexes raising ``TypeError`` for ``method="ffill"`` and ``method="bfill"`` and specified ``tolerance`` (:issue:`38566`)
284285
- Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` with empty :class:`DataFrame` and specified columns for string indexer and non empty :class:`DataFrame` to set (:issue:`38831`)

pandas/core/frame.py

+5
Original file line numberDiff line numberDiff line change
@@ -3195,6 +3195,11 @@ def __setitem__(self, key, value):
31953195
self._setitem_array(key, value)
31963196
elif isinstance(value, DataFrame):
31973197
self._set_item_frame_value(key, value)
3198+
elif is_list_like(value) and 1 < len(
3199+
self.columns.get_indexer_for([key])
3200+
) == len(value):
3201+
# Column to set is duplicated
3202+
self._setitem_array([key], value)
31983203
else:
31993204
# set column
32003205
self._set_item(key, value)

pandas/tests/frame/indexing/test_setitem.py

+18
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,24 @@ def test_setitem_frame_length_0_str_key(self, indexer):
348348
expected["A"] = expected["A"].astype("object")
349349
tm.assert_frame_equal(df, expected)
350350

351+
def test_setitem_frame_duplicate_columns(self):
352+
# GH#15695
353+
cols = ["A", "B", "C"] * 2
354+
df = DataFrame(index=range(3), columns=cols)
355+
df.loc[0, "A"] = (0, 3)
356+
df.loc[:, "B"] = (1, 4)
357+
df["C"] = (2, 5)
358+
expected = DataFrame(
359+
[
360+
[0, 1, 2, 3, 4, 5],
361+
[np.nan, 1, 2, np.nan, 4, 5],
362+
[np.nan, 1, 2, np.nan, 4, 5],
363+
],
364+
columns=cols,
365+
dtype="object",
366+
)
367+
tm.assert_frame_equal(df, expected)
368+
351369

352370
class TestDataFrameSetItemWithExpansion:
353371
def test_setitem_listlike_views(self):

0 commit comments

Comments
 (0)