Skip to content

Commit

Permalink
Make the sel error more descriptive when method is unset (#6774)
Browse files Browse the repository at this point in the history
* Make the sel error more descriptive when `method` is unset

* Apply suggestions from code review

Co-authored-by: Deepak Cherian <[email protected]>

Co-authored-by: Deepak Cherian <[email protected]>
  • Loading branch information
jsignell and dcherian committed Jul 12, 2022
1 parent 7cc6cc9 commit 4aae7fd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
9 changes: 8 additions & 1 deletion xarray/core/indexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 4aae7fd

Please sign in to comment.