Skip to content

Backport PR #48890 on branch 1.5.x (ERR: Improve error message when assigning a complete row using 'at' m…) #49310

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
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 8 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
function as nv,
np_percentile_argname,
)
from pandas.errors import InvalidIndexError
from pandas.util._decorators import (
Appender,
Substitution,
Expand Down Expand Up @@ -4220,6 +4221,13 @@ def _set_value(
self.loc[index, col] = value
self._item_cache.pop(col, None)

except InvalidIndexError as ii_err:
# GH48729: Seems like you are trying to assign a value to a
# row when only scalar options are permitted
raise InvalidIndexError(
f"You can only assign a scalar value not a {type(value)}"
) from ii_err

def _ensure_valid_index(self, value) -> None:
"""
Ensure that if we don't have an index, that we can create one from the
Expand Down
18 changes: 16 additions & 2 deletions pandas/tests/indexing/test_at.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,12 @@ def test_at_frame_raises_key_error2(self, indexer_al):
def test_at_frame_multiple_columns(self):
# GH#48296 - at shouldn't modify multiple columns
df = DataFrame({"a": [1, 2], "b": [3, 4]})
with pytest.raises(InvalidIndexError, match=r"slice\(None, None, None\)"):
df.at[5] = [6, 7]
new_row = [6, 7]
with pytest.raises(
InvalidIndexError,
match=f"You can only assign a scalar value not a \\{type(new_row)}",
):
df.at[5] = new_row

def test_at_getitem_mixed_index_no_fallback(self):
# GH#19860
Expand All @@ -220,3 +224,13 @@ def test_at_categorical_integers(self):
for key in [0, 1]:
with pytest.raises(KeyError, match=str(key)):
df.at[key, key]

def test_at_applied_for_rows(self):
# GH#48729 .at should raise InvalidIndexError when assigning rows
df = DataFrame(index=["a"], columns=["col1", "col2"])
new_row = [123, 15]
with pytest.raises(
InvalidIndexError,
match=f"You can only assign a scalar value not a \\{type(new_row)}",
):
df.at["a"] = new_row