Skip to content

Commit 530e460

Browse files
authored
ERR: Add explicit error message for isetitem for DataFrame (#51701)
1 parent cb04202 commit 530e460

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

doc/source/whatsnew/v2.1.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ enhancement2
2828

2929
Other enhancements
3030
^^^^^^^^^^^^^^^^^^
31-
-
31+
- Improve error message when setting :class:`DataFrame` with wrong number of columns through :meth:`DataFrame.isetitem` (:issue:`51701`)
3232
-
3333

3434
.. ---------------------------------------------------------------------------

pandas/core/frame.py

+6
Original file line numberDiff line numberDiff line change
@@ -3897,6 +3897,12 @@ def isetitem(self, loc, value) -> None:
38973897
if is_scalar(loc):
38983898
loc = [loc]
38993899

3900+
if len(loc) != len(value.columns):
3901+
raise ValueError(
3902+
f"Got {len(loc)} positions but value has {len(value.columns)} "
3903+
f"columns."
3904+
)
3905+
39003906
for i, idx in enumerate(loc):
39013907
arraylike = self._sanitize_column(value.iloc[:, i])
39023908
self._iset_item_mgr(idx, arraylike, inplace=False)

pandas/tests/frame/methods/test_isetitem.py

+13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import pytest
2+
13
from pandas import (
24
DataFrame,
35
Series,
@@ -35,3 +37,14 @@ def test_isetitem_ea_df_scalar_indexer(self):
3537
}
3638
)
3739
tm.assert_frame_equal(df, expected)
40+
41+
def test_isetitem_dimension_missmatch(self):
42+
# GH#51701
43+
df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]})
44+
value = df.copy()
45+
with pytest.raises(ValueError, match="Got 2 positions but value has 3 columns"):
46+
df.isetitem([1, 2], value)
47+
48+
value = df.copy()
49+
with pytest.raises(ValueError, match="Got 2 positions but value has 1 columns"):
50+
df.isetitem([1, 2], value[["a"]])

0 commit comments

Comments
 (0)