diff --git a/doc/whats-new.rst b/doc/whats-new.rst index e933030e356..c3dde2e6a5a 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -26,6 +26,10 @@ Deprecations Bug Fixes ~~~~~~~~~ +- Empty slices with a negative step, such as ``slice(1, 1, -1)``, on lazily indexed + backend arrays now select nothing, as in NumPy, instead of raising ``IndexError`` + or selecting the whole axis (:issue:`11981`). + By `Ooi Pin Jun `_. - :py:meth:`Dataset.plot.quiver` now aligns hue values with the plotted vectors, so missing hue values mask the correct arrows (:issue:`8928`). diff --git a/xarray/core/indexing.py b/xarray/core/indexing.py index 4b365febfbf..0b583e74b00 100644 --- a/xarray/core/indexing.py +++ b/xarray/core/indexing.py @@ -279,6 +279,8 @@ def normalize_slice(sl: slice, size: int) -> slice: slice(9, None, -1) """ start, stop, step = sl.indices(size) + if start < 0: + return slice(0, 0, 1) return slice(start, stop if stop >= 0 else None, step) @@ -1280,6 +1282,8 @@ def _decompose_slice(key: slice, size: int) -> tuple[slice, slice]: if step > 0: # If key already has a positive step, use it as is in the backend return key, slice(None) + elif start <= stop: + return slice(0, 0), slice(None) else: # determine stop precisely for step > 1 case # Use the range object to do the calculation diff --git a/xarray/tests/test_indexing.py b/xarray/tests/test_indexing.py index 047bf795914..9c301a5276e 100644 --- a/xarray/tests/test_indexing.py +++ b/xarray/tests/test_indexing.py @@ -8,6 +8,7 @@ import pytest from xarray import DataArray, Dataset, Variable, concat +from xarray.backends import BackendArray from xarray.core import indexing, nputils from xarray.core.indexes import PandasIndex, PandasMultiIndex from xarray.core.types import T_Xarray @@ -305,6 +306,7 @@ class TestLazyArray: (slice(None), 4, slice(0, 4, 1)), (slice(1, -3), 7, slice(1, 4, 1)), (slice(None, None, -1), 8, slice(7, None, -1)), + (slice(-4, None, -1), 3, slice(0, 0, 1)), (np.array([-1, 3, -2]), 5, np.array([4, 3, 3])), ), ) @@ -815,9 +817,16 @@ def get_indexers( @pytest.mark.parametrize("size", [100, 99]) @pytest.mark.parametrize( - "sl", [slice(1, -1, 1), slice(None, -1, 2), slice(-1, 1, -1), slice(-1, 1, -2)] + "sl", + [ + slice(1, -1, 1), + slice(None, -1, 2), + slice(-1, 1, -1), + slice(-1, 1, -2), + slice(1, 1, -1), + ], ) -def test_decompose_slice(size, sl) -> None: +def test_decompose_slice(size: int, sl: slice) -> None: x = np.arange(size) slice1, slice2 = indexing._decompose_slice(sl, size) expected = x[sl] @@ -1287,6 +1296,24 @@ def test_backend_indexing_non_numpy() -> None: np.testing.assert_array_equal(indexed.array, np.array([1])) +@pytest.mark.parametrize("key", [slice(1, 1, -1), slice(-4, None, -1)]) +def test_lazily_indexed_empty_negative_step_slice(key: slice) -> None: + data = np.arange(3.0) + + class BasicBackendArray(BackendArray): + shape = data.shape + dtype = data.dtype + + def __getitem__(self, key: indexing.ExplicitIndexer) -> np.ndarray: + return indexing.explicit_indexing_adapter( + key, self.shape, indexing.IndexingSupport.BASIC, data.__getitem__ + ) + + variable = Variable("x", indexing.LazilyIndexedArray(BasicBackendArray())) + actual = variable.isel(x=key).load() + assert actual.shape == data[key].shape == (0,) + + @requires_pandas_3 def test_pandas_StringDtype_index_coerces_to_numpy() -> None: da = DataArray([0, 1], coords={"x": ["x1", "x2"]})