Skip to content

Fix RangeIndex slicing #10471

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 2 commits into from
Jul 1, 2025
Merged

Conversation

benbovy
Copy link
Member

@benbovy benbovy commented Jun 30, 2025

@@ -84,9 +84,9 @@ def slice(self, sl: slice) -> "RangeCoordinateTransform":
# TODO: support reverse transform (i.e., start > stop)?
assert sl.start < sl.stop

new_size = (sl.stop - sl.start) // sl.step
Copy link
Contributor

@dcherian dcherian Jun 30, 2025

Choose a reason for hiding this comment

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

One trick I have learned is to use range objects to outsource this logic to CPython (e.g. #7586)

So you could do:

newrange = range(self.size)[sl]
start = newrange.start
step = newrange.step or 1
size = len(newrange)

Copy link
Member Author

Choose a reason for hiding this comment

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

Nice trick, this also allows supporting reverse indexing without additional effort.

Copy link
Contributor

Choose a reason for hiding this comment

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

Actually, I remember the real API is slice.indices(size) so an alternative is :

        start, stop, step = slicer.indices(self.size)
        size = len(range(start, stop, step))

I think you still need to construct the range object to get the right size so not much difference

This also enables support for reverse slicing (added tests)
@dcherian dcherian merged commit f778624 into pydata:main Jul 1, 2025
31 of 33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

slicing DataArray with RangeIndex coordinate can put coordinate in inconsistent state
2 participants