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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

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.

This also enables support for reverse slicing (added tests)
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