pydata / pydata/xarray

`.sel` with `method` doesn't work for slices

Open
#10,710 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug enhancement topic-indexing topic-pandas-like upstream issue
Dominant language
Python
Stars
4.2k
Forks
1.4k
Avg merge
2d 15h
Merged PRs (30d)
14

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the Dataset.sel entry point and trace how slice indexers reach pandas.Index.slice_indexer and point indexers use pandas.Index.get_indexer. Compare the handling of integer and non-integer slice bounds, including method and tolerance behavior. Done means slice selection accepts method without raising NotImplementedError and returns the expected bounds for the reported examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
pandas, python
Domain
data
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.