Skip to content

Commit 7e410c1

Browse files
authored
CLN: Ensure that setitem ops don't coerce values (#51671)
1 parent ced9833 commit 7e410c1

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

pandas/core/frame.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4757,6 +4757,14 @@ def insert(
47574757
if not isinstance(loc, int):
47584758
raise TypeError("loc must be int")
47594759

4760+
if isinstance(value, DataFrame) and len(value.columns) > 1:
4761+
raise ValueError(
4762+
f"Expected a one-dimensional object, got a DataFrame with "
4763+
f"{len(value.columns)} columns instead."
4764+
)
4765+
elif isinstance(value, DataFrame):
4766+
value = value.iloc[:, 0]
4767+
47604768
value = self._sanitize_column(value)
47614769
self._mgr.insert(loc, column, value)
47624770

@@ -4843,11 +4851,9 @@ def _sanitize_column(self, value) -> ArrayLike:
48434851
"""
48444852
self._ensure_valid_index(value)
48454853

4846-
# We can get there through isetitem with a DataFrame
4847-
# or through loc single_block_path
4848-
if isinstance(value, DataFrame):
4849-
return _reindex_for_setitem(value, self.index)
4850-
elif is_dict_like(value):
4854+
# Using a DataFrame would mean coercing values to one dtype
4855+
assert not isinstance(value, DataFrame)
4856+
if is_dict_like(value):
48514857
return _reindex_for_setitem(Series(value), self.index)
48524858

48534859
if is_list_like(value):

pandas/tests/frame/indexing/test_insert.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ def test_insert_frame(self):
100100
# GH#42403
101101
df = DataFrame({"col1": [1, 2], "col2": [3, 4]})
102102

103-
msg = r"Expected a 1D array, got an array with shape \(2, 2\)"
103+
msg = (
104+
"Expected a one-dimensional object, got a DataFrame with 2 columns instead."
105+
)
104106
with pytest.raises(ValueError, match=msg):
105107
df.insert(1, "newcol", df)

0 commit comments

Comments
 (0)