Skip to content

CLN: Ensure that setitem ops don't coerce values #51671

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
Feb 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
16 changes: 11 additions & 5 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4757,6 +4757,14 @@ def insert(
if not isinstance(loc, int):
raise TypeError("loc must be int")

if isinstance(value, DataFrame) and len(value.columns) > 1:
raise ValueError(
f"Expected a one-dimensional object, got a DataFrame with "
f"{len(value.columns)} instead."
)
elif isinstance(value, DataFrame):
value = value.iloc[:, 0]

value = self._sanitize_column(value)
self._mgr.insert(loc, column, value)

Expand Down Expand Up @@ -4843,11 +4851,9 @@ def _sanitize_column(self, value) -> ArrayLike:
"""
self._ensure_valid_index(value)

# We can get there through isetitem with a DataFrame
# or through loc single_block_path
if isinstance(value, DataFrame):
return _reindex_for_setitem(value, self.index)
elif is_dict_like(value):
# Using a DataFrame would mean coercing values to one dtype
assert not isinstance(value, DataFrame)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no other cases that can be affected by disallowing this here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

None that I can think of or find. Isetitem iterates over the columns now. Don’t think that we can get here with a DataFrame now

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for checking.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not for this PR, but some things I saw while double-checking:

in isetitem isinstance(value, DataFrame) case should we check that len(loc) == len(value.columns)?
_iset_item is only called from _replace_columnwise, where we know we have a Series with matching index, might be simpler to skip sanitize_column?
Might make sense to refactor _set_item back into __setitem__, as the latter isn't that complicated and the former has a name really similar to a bunch of other names

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Yes we should probably raise if they don't match
  2. Should be faster at least
  3. Makes setitem pretty long, but shouldn't really hurt?

if is_dict_like(value):
return _reindex_for_setitem(Series(value), self.index)

if is_list_like(value):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/frame/indexing/test_insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,6 @@ def test_insert_frame(self):
# GH#42403
df = DataFrame({"col1": [1, 2], "col2": [3, 4]})

msg = r"Expected a 1D array, got an array with shape \(2, 2\)"
msg = "Expected a one-dimensional object, got a DataFrame with 2 instead."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"2" here sounds like it is referring to 2 dimensions, which is accurate but i think not intended

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yikes yes, I forgot to add columns, thx

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated, otherwise ok?

I think making this stricter helps in the long run

with pytest.raises(ValueError, match=msg):
df.insert(1, "newcol", df)