Skip to content

.sel with method doesn't work for slices #10710

@TomNicholas

Description

@TomNicholas

What happened?

ds = xr.Dataset(
    coords={"lat": ("lat", [20, 21, 22, 23])}
)
ds.sel(lat=slice(21, 22), method="nearest")
NotImplementedError: cannot use ``method`` argument if any indexers are slice objects

What did you expect to happen?

This to return

xr.Dataset(
    coords={"lat": ("lat", [21, 22])}
)

which is what is returned by

ds.sel(lat=slice(21, 22))

I also expect this to work for non-integers too, as it does when selecting points rather than slices.

Minimal Complete Verifiable Example

MVCE confirmation

  • Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
  • Complete example — the example is self-contained, including all data and the text of any traceback.
  • Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
  • New issue — a search of GitHub Issues suggests this is not a duplicate.
  • Recent environment — the issue occurs with the latest version of xarray and its dependencies.

Relevant log output

Anything else we need to know?

It looks like the core reason this isn't implemented is because whilst pandas.Index.get_indexer supports method and tolerance for point selection, pandas.Index.slice_indexer does not support those kwargs.

But it does seem like it should be possible to work around this for simple cases in xarray, by simply calling pandas.Index.get_indexer once to get the start position of the slice, and again to get the end position of the slice.

Environment

main

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions