diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 45b5c16415f9d..dd27fd9e128ae 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -28,7 +28,7 @@ enhancement2 Other enhancements ^^^^^^^^^^^^^^^^^^ -- +- Improve error message when setting :class:`DataFrame` with wrong number of columns through :meth:`DataFrame.isetitem` (:issue:`51701`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index dbbe2c0751f3a..bac835cd35d8e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3897,6 +3897,12 @@ def isetitem(self, loc, value) -> None: if is_scalar(loc): loc = [loc] + if len(loc) != len(value.columns): + raise ValueError( + f"Got {len(loc)} positions but value has {len(value.columns)} " + f"columns." + ) + for i, idx in enumerate(loc): arraylike = self._sanitize_column(value.iloc[:, i]) self._iset_item_mgr(idx, arraylike, inplace=False) diff --git a/pandas/tests/frame/methods/test_isetitem.py b/pandas/tests/frame/methods/test_isetitem.py index 59328aafefefb..e8064cbc44d5f 100644 --- a/pandas/tests/frame/methods/test_isetitem.py +++ b/pandas/tests/frame/methods/test_isetitem.py @@ -1,3 +1,5 @@ +import pytest + from pandas import ( DataFrame, Series, @@ -35,3 +37,14 @@ def test_isetitem_ea_df_scalar_indexer(self): } ) tm.assert_frame_equal(df, expected) + + def test_isetitem_dimension_missmatch(self): + # GH#51701 + df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}) + value = df.copy() + with pytest.raises(ValueError, match="Got 2 positions but value has 3 columns"): + df.isetitem([1, 2], value) + + value = df.copy() + with pytest.raises(ValueError, match="Got 2 positions but value has 1 columns"): + df.isetitem([1, 2], value[["a"]])