Skip to content

Commit 4aae7fd

Browse files
jsignelldcherian
andauthored
Make the sel error more descriptive when method is unset (#6774)
* 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]>
1 parent 7cc6cc9 commit 4aae7fd

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

xarray/core/indexes.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,14 @@ def sel(
404404
f"not all values found in index {coord_name!r}"
405405
)
406406
else:
407-
indexer = self.index.get_loc(label_value)
407+
try:
408+
indexer = self.index.get_loc(label_value)
409+
except KeyError as e:
410+
raise KeyError(
411+
f"not all values found in index {coord_name!r}. "
412+
"Try setting the `method` keyword argument (example: method='nearest')."
413+
) from e
414+
408415
elif label_array.dtype.kind == "b":
409416
indexer = label_array
410417
else:

xarray/tests/test_dataarray.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1054,6 +1054,9 @@ def test_sel_no_index(self) -> None:
10541054
def test_sel_method(self) -> None:
10551055
data = DataArray(np.random.randn(3, 4), [("x", [0, 1, 2]), ("y", list("abcd"))])
10561056

1057+
with pytest.raises(KeyError, match="Try setting the `method`"):
1058+
data.sel(y="ab")
1059+
10571060
expected = data.sel(y=["a", "b"])
10581061
actual = data.sel(y=["ab", "ba"], method="pad")
10591062
assert_identical(expected, actual)

0 commit comments

Comments
 (0)