Skip to content

slicing a slice with an array without expanding the slice #10580

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Aug 12, 2025
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions xarray/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
get_valid_numpy_dtype,
is_duck_array,
is_duck_dask_array,
is_full_slice,
is_scalar,
is_valid_numpy_dtype,
to_0d_array,
Expand All @@ -41,6 +42,9 @@
from xarray.namedarray._typing import _Shape, duckarray
from xarray.namedarray.parallelcompat import ChunkManagerEntrypoint

BasicIndexerType = int | np.integer | slice
OuterIndexerType = BasicIndexerType | np.ndarray[Any, np.dtype[np.integer]]


@dataclass
class IndexSelResult:
Expand Down Expand Up @@ -298,17 +302,52 @@ def slice_slice(old_slice: slice, applied_slice: slice, size: int) -> slice:
return slice(start, stop, step)


def _index_indexer_1d(old_indexer, applied_indexer, size: int):
if isinstance(applied_indexer, slice) and applied_indexer == slice(None):
def slice_slice_by_array(
old_slice: slice,
array: np.ndarray[Any, np.dtype[np.integer]],
size: int,
) -> np.ndarray[Any, np.dtype[np.integer]]:
"""Given a slice and the size of the dimension to which it will be applied,
index it with an array to return a new array equivalent to applying
the slices sequentially

Examples
--------
>>> slice_slice_by_array(slice(2, 10), np.array([1, 3, 5]), 12)
array([3, 5, 7])
>>> slice_slice_by_array(slice(1, None, 2), np.array([1, 3, 7, 8]), 20)
array([ 3, 7, 15, 17])
>>> slice_slice_by_array(slice(None, None, -1), np.array([2, 4, 7]), 20)
array([17, 15, 12])
"""
# to get a concrete slice, limited to the size of the array
normalized = normalize_slice(old_slice, size)

new_indexer = array * normalized.step + normalized.start

if np.any(new_indexer >= size):
raise IndexError("indices out of bounds") # TODO: more helpful error message

return new_indexer


def _index_indexer_1d(
old_indexer: OuterIndexerType,
applied_indexer: OuterIndexerType,
size: int,
) -> OuterIndexerType:
if is_full_slice(applied_indexer):
# shortcut for the usual case
return old_indexer
if isinstance(old_indexer, slice):
if isinstance(applied_indexer, slice):
indexer = slice_slice(old_indexer, applied_indexer, size)
elif isinstance(applied_indexer, integer_types):
indexer = range(*old_indexer.indices(size))[applied_indexer] # type: ignore[assignment]
elif is_full_slice(old_indexer):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this fix point (3) in #10311 (comment)

This is "combined" with the arrayized version of BasicIndexer(slice(None), slice(None), slice(None))

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, because for vectorized indexing we use _combine_indexers, not _index_indexer_1d (but see also my comment in #10311 about whether we can frame that particular case – fancy indexing along a single dimension – as an outer indexer)

indexer = applied_indexer
else:
indexer = _expand_slice(old_indexer, size)[applied_indexer]
indexer = slice_slice_by_array(old_indexer, applied_indexer, size)
else:
indexer = old_indexer[applied_indexer]
return indexer
Expand Down Expand Up @@ -387,7 +426,7 @@ class BasicIndexer(ExplicitIndexer):

__slots__ = ()

def __init__(self, key: tuple[int | np.integer | slice, ...]):
def __init__(self, key: tuple[BasicIndexerType, ...]):
if not isinstance(key, tuple):
raise TypeError(f"key must be a tuple: {key!r}")

Expand Down Expand Up @@ -419,9 +458,7 @@ class OuterIndexer(ExplicitIndexer):

def __init__(
self,
key: tuple[
int | np.integer | slice | np.ndarray[Any, np.dtype[np.generic]], ...
],
key: tuple[BasicIndexerType | np.ndarray[Any, np.dtype[np.generic]], ...],
):
if not isinstance(key, tuple):
raise TypeError(f"key must be a tuple: {key!r}")
Expand Down
14 changes: 14 additions & 0 deletions xarray/tests/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,20 @@ def test_slice_slice(self) -> None:
actual = x[new_slice]
assert_array_equal(expected, actual)

@pytest.mark.parametrize(
["old_slice", "array", "size", "expected"],
(
(slice(None, 8), np.arange(2, 6), 10, np.arange(2, 6)),
(slice(2, None), np.arange(2, 6), 10, np.arange(4, 8)),
(slice(1, 10, 2), np.arange(1, 4), 15, np.arange(3, 8, 2)),
(slice(10, None, -1), np.array([2, 5, 7]), 12, np.array([8, 5, 3])),
),
)
def test_slice_slice_by_array(self, old_slice, array, size, expected):
actual = indexing.slice_slice_by_array(old_slice, array, size)

assert_array_equal(actual, expected)

def test_lazily_indexed_array(self) -> None:
original = np.random.rand(10, 20, 30)
x = indexing.NumpyIndexingAdapter(original)
Expand Down
Loading