diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index f155fb27d0de5..af14856fa3b6a 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -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*** diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9f16340d98e22..5d05983529fba 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -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]] diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index bd916f230bead..bc632209ff7e1 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -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