Skip to content

BUG: Fix error message for assigning a column with an empty DataFrame #56120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -496,6 +496,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