Skip to content

Commit

Permalink
BUG: Fix error message for assigning a column with an empty DataFrame (
Browse files Browse the repository at this point in the history
  • Loading branch information
rob-sil authored Nov 22, 2023
1 parent 4cd6d7e commit 68ef1da
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,7 @@ Other
- Bug in :meth:`Dataframe.from_dict` which would always sort the rows of the created :class:`DataFrame`. (:issue:`55683`)
- Bug in rendering ``inf`` values inside a a :class:`DataFrame` with the ``use_inf_as_na`` option enabled (:issue:`55483`)
- Bug in rendering a :class:`Series` with a :class:`MultiIndex` when one of the index level's names is 0 not having that name displayed (:issue:`55415`)
- Bug in the error message when assigning an empty dataframe to a column (:issue:`55956`)

.. ***DO NOT USE THIS SECTION***
Expand Down
6 changes: 5 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4375,11 +4375,15 @@ def _set_item_frame_value(self, key, value: DataFrame) -> None:

return self.isetitem(locs, value)

if len(value.columns) != 1:
if len(value.columns) > 1:
raise ValueError(
"Cannot set a DataFrame with multiple columns to the single "
f"column {key}"
)
elif len(value.columns) == 0:
raise ValueError(
f"Cannot set a DataFrame without columns to the column {key}"
)

self[key] = value[value.columns[0]]

Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/frame/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ def test_setitem_error_msmgs(self):
with pytest.raises(ValueError, match=msg):
df["gr"] = df.groupby(["b", "c"]).count()

# GH 55956, specific message for zero columns
msg = "Cannot set a DataFrame without columns to the column gr"
with pytest.raises(ValueError, match=msg):
df["gr"] = DataFrame()

def test_setitem_benchmark(self):
# from the vb_suite/frame_methods/frame_insert_columns
N = 10
Expand Down

0 comments on commit 68ef1da

Please sign in to comment.