From 83f562e2c2d57e1b0c8c570a84c4405c1ddbc198 Mon Sep 17 00:00:00 2001 From: Ambuj Pawar Date: Mon, 24 Oct 2022 23:06:49 +0200 Subject: [PATCH] =?UTF-8?q?Backport=20PR=20#48890:=20ERR:=20Improve=20erro?= =?UTF-8?q?r=20message=20when=20assigning=20a=20complete=20row=20using=20'?= =?UTF-8?q?at'=20m=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pandas/core/frame.py | 8 ++++++++ pandas/tests/indexing/test_at.py | 18 ++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b525bf6f57e88..d3116f83d58cb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -86,6 +86,7 @@ function as nv, np_percentile_argname, ) +from pandas.errors import InvalidIndexError from pandas.util._decorators import ( Appender, Substitution, @@ -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 diff --git a/pandas/tests/indexing/test_at.py b/pandas/tests/indexing/test_at.py index 1e502ca70189a..adbc0e2f8127a 100644 --- a/pandas/tests/indexing/test_at.py +++ b/pandas/tests/indexing/test_at.py @@ -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 @@ -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