Skip to content

Commit b44f1cd

Browse files
ambujpawarAmbuj Pawar
and
Ambuj Pawar
authored
ERR: Improve error message when assigning a complete row using 'at' m… (#48890)
* ERR: Improve error message when assigning a complete row using 'at' method * fix precommit issues * Fix: Review comments * Fix: precommit issues * Raise InvalidIndexError from original exception * Raise InvalidIndex error from original error * fix failing tests * fix failing tests Co-authored-by: Ambuj Pawar <[email protected]>
1 parent a2d5564 commit b44f1cd

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
@@ -91,6 +91,7 @@
9191
function as nv,
9292
np_percentile_argname,
9393
)
94+
from pandas.errors import InvalidIndexError
9495
from pandas.util._decorators import (
9596
Appender,
9697
Substitution,
@@ -4199,6 +4200,13 @@ def _set_value(
41994200
self.loc[index, col] = value
42004201
self._item_cache.pop(col, None)
42014202

4203+
except InvalidIndexError as ii_err:
4204+
# GH48729: Seems like you are trying to assign a value to a
4205+
# row when only scalar options are permitted
4206+
raise InvalidIndexError(
4207+
f"You can only assign a scalar value not a {type(value)}"
4208+
) from ii_err
4209+
42024210
def _ensure_valid_index(self, value) -> None:
42034211
"""
42044212
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
@@ -211,8 +211,12 @@ def test_at_frame_raises_key_error2(self, indexer_al):
211211
def test_at_frame_multiple_columns(self):
212212
# GH#48296 - at shouldn't modify multiple columns
213213
df = DataFrame({"a": [1, 2], "b": [3, 4]})
214-
with pytest.raises(InvalidIndexError, match=r"slice\(None, None, None\)"):
215-
df.at[5] = [6, 7]
214+
new_row = [6, 7]
215+
with pytest.raises(
216+
InvalidIndexError,
217+
match=f"You can only assign a scalar value not a \\{type(new_row)}",
218+
):
219+
df.at[5] = new_row
216220

217221
def test_at_getitem_mixed_index_no_fallback(self):
218222
# GH#19860
@@ -234,3 +238,13 @@ def test_at_categorical_integers(self):
234238
for key in [0, 1]:
235239
with pytest.raises(KeyError, match=str(key)):
236240
df.at[key, key]
241+
242+
def test_at_applied_for_rows(self):
243+
# GH#48729 .at should raise InvalidIndexError when assigning rows
244+
df = DataFrame(index=["a"], columns=["col1", "col2"])
245+
new_row = [123, 15]
246+
with pytest.raises(
247+
InvalidIndexError,
248+
match=f"You can only assign a scalar value not a \\{type(new_row)}",
249+
):
250+
df.at["a"] = new_row

0 commit comments

Comments
 (0)