diff --git a/xarray/core/indexes.py b/xarray/core/indexes.py index ee3ef17ed65..8589496b5eb 100644 --- a/xarray/core/indexes.py +++ b/xarray/core/indexes.py @@ -404,7 +404,14 @@ def sel( f"not all values found in index {coord_name!r}" ) else: - indexer = self.index.get_loc(label_value) + try: + indexer = self.index.get_loc(label_value) + except KeyError as e: + raise KeyError( + f"not all values found in index {coord_name!r}. " + "Try setting the `method` keyword argument (example: method='nearest')." + ) from e + elif label_array.dtype.kind == "b": indexer = label_array else: diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index 5efcea1283f..f26fc1c9d5e 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -1054,6 +1054,9 @@ def test_sel_no_index(self) -> None: def test_sel_method(self) -> None: data = DataArray(np.random.randn(3, 4), [("x", [0, 1, 2]), ("y", list("abcd"))]) + with pytest.raises(KeyError, match="Try setting the `method`"): + data.sel(y="ab") + expected = data.sel(y=["a", "b"]) actual = data.sel(y=["ab", "ba"], method="pad") assert_identical(expected, actual)