diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 15c5cc97b8426..a9c49b7476fa6 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -197,7 +197,7 @@ Strings Indexing ^^^^^^^^ -- +- The traceback from a ``KeyError`` when asking ``.loc`` for a single missing label is now shorter and more clear (:issue:`21557`) - - diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index d5e81105dd323..38b6aaa2230fb 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1807,8 +1807,6 @@ def error(): try: key = self._convert_scalar_indexer(key, axis) - if not ax.contains(key): - error() except TypeError as e: # python 3 type errors should be raised @@ -1818,6 +1816,9 @@ def error(): except: error() + if not ax.contains(key): + error() + def _is_scalar_access(self, key): # this is a shortcut accessor to both .loc and .iloc # that provide the equivalent access of .at and .iat