Skip to content

Commit ebcc47b

Browse files
Backport PR pandas-dev#48890 on branch 1.5.x (ERR: Improve error message when assigning a complete row using 'at' m…) (pandas-dev#49310)
Backport PR pandas-dev#48890: ERR: Improve error message when assigning a complete row using 'at' m… Co-authored-by: Ambuj Pawar <[email protected]>
1 parent 722fbc3 commit ebcc47b

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

pandas/core/frame.py

+8
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
function as nv,
8787
np_percentile_argname,
8888
)
89+
from pandas.errors import InvalidIndexError
8990
from pandas.util._decorators import (
9091
Appender,
9192
Substitution,
@@ -4220,6 +4221,13 @@ def _set_value(
42204221
self.loc[index, col] = value
42214222
self._item_cache.pop(col, None)
42224223

4224+
except InvalidIndexError as ii_err:
4225+
# GH48729: Seems like you are trying to assign a value to a
4226+
# row when only scalar options are permitted
4227+
raise InvalidIndexError(
4228+
f"You can only assign a scalar value not a {type(value)}"
4229+
) from ii_err
4230+
42234231
def _ensure_valid_index(self, value) -> None:
42244232
"""
42254233
Ensure that if we don't have an index, that we can create one from the

pandas/tests/indexing/test_at.py

+16-2
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,12 @@ def test_at_frame_raises_key_error2(self, indexer_al):
197197
def test_at_frame_multiple_columns(self):
198198
# GH#48296 - at shouldn't modify multiple columns
199199
df = DataFrame({"a": [1, 2], "b": [3, 4]})
200-
with pytest.raises(InvalidIndexError, match=r"slice\(None, None, None\)"):
201-
df.at[5] = [6, 7]
200+
new_row = [6, 7]
201+
with pytest.raises(
202+
InvalidIndexError,
203+
match=f"You can only assign a scalar value not a \\{type(new_row)}",
204+
):
205+
df.at[5] = new_row
202206

203207
def test_at_getitem_mixed_index_no_fallback(self):
204208
# GH#19860
@@ -220,3 +224,13 @@ def test_at_categorical_integers(self):
220224
for key in [0, 1]:
221225
with pytest.raises(KeyError, match=str(key)):
222226
df.at[key, key]
227+
228+
def test_at_applied_for_rows(self):
229+
# GH#48729 .at should raise InvalidIndexError when assigning rows
230+
df = DataFrame(index=["a"], columns=["col1", "col2"])
231+
new_row = [123, 15]
232+
with pytest.raises(
233+
InvalidIndexError,
234+
match=f"You can only assign a scalar value not a \\{type(new_row)}",
235+
):
236+
df.at["a"] = new_row

0 commit comments

Comments
 (0)