Skip to content

Fix RangeIndex.isel with negative positions and boolean masks - #11986

Open
parabol123654 wants to merge 1 commit into
pydata:mainfrom
parabol123654:fix-range-index-isel
Open

parabol123654 wants to merge 1 commit into
pydata:mainfrom
parabol123654:fix-range-index-isel

Conversation

@parabol123654

Copy link
Copy Markdown

Description

ds.isel(x=[-1, -2]) on a dimension with a RangeIndex gives x = [-1., -2.] instead of [4., 3.], and a boolean mask gives labels like [0., 1., 0., 1., 1.] (mask times step), which then doesn't match the length of the data. With a DataArray mask it fails with "conflicting sizes". RangeIndex.isel passes the raw key to the transform, so I now convert boolean keys with np.flatnonzero and wrap negative positions before that, without materializing the range.

The new test fails on main and passes with the fix; test_range_index.py, test_indexes.py, test_coordinate_transform.py and test_indexing.py pass.

Checklist

  • Tests added
  • User visible changes (including notable bug fixes) are documented in whats-new.rst

AI Disclosure

  • This PR contains AI-generated content.
    • I have tested any AI-generated content in my PR.
    • I take responsibility for any AI-generated content in my PR.
      Tools: Claude Code. It found the bug while checking RangeIndex indexing against numpy and wrote the fix and test; I reproduced it, read the change and reran the tests myself.

[This is Claude Code on behalf of Manh Nguyen]

RangeIndex.isel computes the labels of the new PandasIndex as
start + key * step, using the raw array key. Negative positions are not
wrapped and a boolean mask is used as 0/1 instead of being turned into
positions, so the coordinate no longer matches the data:

    ds.isel(x=[-1, -2])                      # x = [-1., -2.], not [4., 3.]
    ds.isel(x=np.array([False, True, True])) # x has 3 labels, data has 2
    ds.isel(x=xr.DataArray(mask, dims="x"))  # ValueError: conflicting sizes

The data variables are indexed correctly, only the index is wrong. This
has been there since RangeIndex was added in pydata#10076.

Convert a boolean key with np.flatnonzero and wrap negative positions
by the index size before calling the transform, like numpy does. This
doesn't build the full range, so the index stays cheap.

Co-authored-by: Claude <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant