Skip to content

API/BUG: make .at raise same exceptions as .loc #31724

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 4 commits into from
Feb 6, 2020
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
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ Backwards incompatible API changes
- :meth:`DataFrameGroupby.mean` and :meth:`SeriesGroupby.mean` (and similarly for :meth:`~DataFrameGroupby.median`, :meth:`~DataFrameGroupby.std`` and :meth:`~DataFrameGroupby.var``)
now raise a ``TypeError`` if a not-accepted keyword argument is passed into it.
Previously a ``UnsupportedFunctionCall`` was raised (``AssertionError`` if ``min_count`` passed into :meth:`~DataFrameGroupby.median``) (:issue:`31485`)

- :meth:`DataFrame.at` and :meth:`Series.at` will raise a ``TypeError`` instead of a ``ValueError`` if an incompatible key is passed, and ``KeyError`` if a missing key is passed, matching the behavior of ``.loc[]`` (:issue:`31722`)
-

.. ---------------------------------------------------------------------------

Expand Down
20 changes: 5 additions & 15 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2100,21 +2100,11 @@ def _convert_key(self, key, is_setter: bool = False):
if is_setter:
return list(key)

for ax, i in zip(self.obj.axes, key):
if ax.is_integer():
if not is_integer(i):
raise ValueError(
"At based indexing on an integer index "
"can only have integer indexers"
)
else:
if is_integer(i) and not (ax.holds_integer() or ax.is_floating()):
raise ValueError(
"At based indexing on an non-integer "
"index can only have non-integer "
"indexers"
)
return key
lkey = list(key)
for n, (ax, i) in enumerate(zip(self.obj.axes, key)):
lkey[n] = ax._convert_scalar_indexer(i, kind="loc")

return tuple(lkey)


@Appender(IndexingMixin.iat.__doc__)
Expand Down
69 changes: 55 additions & 14 deletions pandas/tests/indexing/test_scalar.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,38 +129,79 @@ def test_imethods_with_dups(self):
result = df.iat[2, 0]
assert result == 2

def test_at_to_fail(self):
def test_series_at_raises_type_error(self):
# at should not fallback
# GH 7814
s = Series([1, 2, 3], index=list("abc"))
result = s.at["a"]
# GH#31724 .at should match .loc
ser = Series([1, 2, 3], index=list("abc"))
result = ser.at["a"]
assert result == 1
result = ser.loc["a"]
assert result == 1

msg = (
"At based indexing on an non-integer index can only have "
"non-integer indexers"
"cannot do label indexing on <class 'pandas.core.indexes.base.Index'> "
Copy link
Member

Choose a reason for hiding this comment

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

I have to say that I found the previous error message more readable ..

Copy link
Member Author

Choose a reason for hiding this comment

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

I generally agree, that suggests we should improve the existing messages for "loc"

r"with these indexers \[0\] of <class 'int'>"
)
with pytest.raises(ValueError, match=msg):
s.at[0]
with pytest.raises(TypeError, match=msg):
ser.at[0]
with pytest.raises(TypeError, match=msg):
ser.loc[0]

def test_frame_raises_type_error(self):
# GH#31724 .at should match .loc
df = DataFrame({"A": [1, 2, 3]}, index=list("abc"))
result = df.at["a", "A"]
assert result == 1
with pytest.raises(ValueError, match=msg):
result = df.loc["a", "A"]
assert result == 1

msg = (
"cannot do label indexing on <class 'pandas.core.indexes.base.Index'> "
r"with these indexers \[0\] of <class 'int'>"
)
with pytest.raises(TypeError, match=msg):
df.at["a", 0]
with pytest.raises(TypeError, match=msg):
df.loc["a", 0]

def test_series_at_raises_key_error(self):
# GH#31724 .at should match .loc

s = Series([1, 2, 3], index=[3, 2, 1])
result = s.at[1]
ser = Series([1, 2, 3], index=[3, 2, 1])
result = ser.at[1]
assert result == 3
msg = "At based indexing on an integer index can only have integer indexers"
with pytest.raises(ValueError, match=msg):
s.at["a"]
result = ser.loc[1]
assert result == 3

with pytest.raises(KeyError, match="a"):
ser.at["a"]
with pytest.raises(KeyError, match="a"):
# .at should match .loc
ser.loc["a"]

def test_frame_at_raises_key_error(self):
# GH#31724 .at should match .loc

df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1])

result = df.at[1, 0]
assert result == 3
with pytest.raises(ValueError, match=msg):
result = df.loc[1, 0]
assert result == 3

with pytest.raises(KeyError, match="a"):
df.at["a", 0]
with pytest.raises(KeyError, match="a"):
df.loc["a", 0]

with pytest.raises(KeyError, match="a"):
df.at[1, "a"]
with pytest.raises(KeyError, match="a"):
df.loc[1, "a"]

# TODO: belongs somewhere else?
def test_getitem_list_missing_key(self):
# GH 13822, incorrect error string with non-unique columns when missing
# column is accessed
df = DataFrame({"x": [1.0], "y": [2.0], "z": [3.0]})
Expand Down