| 837 | return self._replace(self.index[indxr]) # type: ignore[index,unused-ignore] |
| 838 | |
| 839 | def sel( |
| 840 | self, labels: dict[Any, Any], method=None, tolerance=None |
| 841 | ) -> IndexSelResult: |
| 842 | from xarray.core.dataarray import DataArray |
| 843 | from xarray.core.variable import Variable |
| 844 | |
| 845 | if method is not None and not isinstance(method, str): |
| 846 | raise TypeError("``method`` must be a string") |
| 847 | |
| 848 | assert len(labels) == 1 |
| 849 | coord_name, label = next(iter(labels.items())) |
| 850 | |
| 851 | if isinstance(label, slice): |
| 852 | indexer = _query_slice(self.index, label, coord_name, method, tolerance) |
| 853 | elif is_dict_like(label): |
| 854 | raise ValueError( |
| 855 | "cannot use a dict-like object for selection on " |
| 856 | "a dimension that does not have a MultiIndex" |
| 857 | ) |
| 858 | else: |
| 859 | label_array = normalize_label(label, dtype=self.coord_dtype) |
| 860 | if label_array.ndim == 0: |
| 861 | label_value = as_scalar(label_array) |
| 862 | if isinstance(self.index, pd.CategoricalIndex): |
| 863 | if method is not None: |
| 864 | raise ValueError( |
| 865 | "'method' is not supported when indexing using a CategoricalIndex." |
| 866 | ) |
| 867 | if tolerance is not None: |
| 868 | raise ValueError( |
| 869 | "'tolerance' is not supported when indexing using a CategoricalIndex." |
| 870 | ) |
| 871 | indexer = self.index.get_loc(label_value) |
| 872 | elif method is not None: |
| 873 | indexer = get_indexer_nd(self.index, label_array, method, tolerance) |
| 874 | if np.any(indexer < 0): |
| 875 | raise KeyError(f"not all values found in index {coord_name!r}") |
| 876 | else: |
| 877 | try: |
| 878 | indexer = self.index.get_loc(label_value) |
| 879 | except KeyError as e: |
| 880 | raise KeyError( |
| 881 | f"not all values found in index {coord_name!r}. " |
| 882 | "Try setting the `method` keyword argument (example: method='nearest')." |
| 883 | ) from e |
| 884 | |
| 885 | elif label_array.dtype.kind == "b": |
| 886 | indexer = label_array |
| 887 | else: |
| 888 | indexer = get_indexer_nd(self.index, label_array, method, tolerance) |
| 889 | if np.any(indexer < 0): |
| 890 | raise KeyError(f"not all values found in index {coord_name!r}") |
| 891 | |
| 892 | # attach dimension names and/or coordinates to positional indexer |
| 893 | if isinstance(label, Variable): |
| 894 | indexer = Variable(label.dims, indexer) |
| 895 | elif isinstance(label, DataArray): |
| 896 | indexer = DataArray(indexer, coords=label._coords, dims=label.dims) |