From e03ae4a0facea2ec8dc68eaa68b09d4660c612f1 Mon Sep 17 00:00:00 2001 From: Julia Signell Date: Mon, 11 Jul 2022 17:04:19 -0400 Subject: [PATCH 1/2] Make the sel error more descriptive when `method` is unset --- xarray/core/indexes.py | 9 ++++++++- xarray/tests/test_dataarray.py | 3 +++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/xarray/core/indexes.py b/xarray/core/indexes.py index ee3ef17ed65..4972e292d8a 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}. " + "Did you mean to set `method=`?" + ) 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 fecc06180a6..966023047de 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -1055,6 +1055,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="Did you mean to set `method=`?"): + data.sel(y="ab") + expected = data.sel(y=["a", "b"]) actual = data.sel(y=["ab", "ba"], method="pad") assert_identical(expected, actual) From bd8579764e7c0eadb7a03533e95ab5fbd78a5448 Mon Sep 17 00:00:00 2001 From: Julia Signell Date: Tue, 12 Jul 2022 14:47:26 -0400 Subject: [PATCH 2/2] Apply suggestions from code review Co-authored-by: Deepak Cherian --- xarray/core/indexes.py | 2 +- xarray/tests/test_dataarray.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/xarray/core/indexes.py b/xarray/core/indexes.py index 4972e292d8a..8589496b5eb 100644 --- a/xarray/core/indexes.py +++ b/xarray/core/indexes.py @@ -409,7 +409,7 @@ def sel( except KeyError as e: raise KeyError( f"not all values found in index {coord_name!r}. " - "Did you mean to set `method=`?" + "Try setting the `method` keyword argument (example: method='nearest')." ) from e elif label_array.dtype.kind == "b": diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index 966023047de..20a9f4d9ad2 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -1055,7 +1055,7 @@ 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="Did you mean to set `method=`?"): + with pytest.raises(KeyError, match="Try setting the `method`"): data.sel(y="ab") expected = data.sel(y=["a", "b"])