Skip to content
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

Make slicing behavior consistent for highly negative offsets #15232

Closed
orlp opened this issue Mar 22, 2024 · 0 comments · Fixed by #15242
Closed

Make slicing behavior consistent for highly negative offsets #15232

orlp opened this issue Mar 22, 2024 · 0 comments · Fixed by #15242
Assignees
Labels
A-ops Area: operations accepted Ready for implementation P-medium Priority: medium

Comments

@orlp
Copy link
Collaborator

orlp commented Mar 22, 2024

This is the current behavior of pl.Series(["abcd"]).str.slice(i, 2), and the other (non-string) slice operations behave similarly:

       -7 ab 
       -6 ab 
       -5 ab 
0 ab   -4 ab 
1 bc   -3 bc 
2 cd   -2 cd 
3 d    -1 d  
4
5

This inconsistency between the left-hand-side and right-hand-side should be fixed, and instead we'd have the following behavior:

        -7    
        -6    
        -5 a  
0 ab    -4 ab 
1 bc    -3 bc 
2 cd    -2 cd 
3 d     -1 d  
4 
5 

To translate from Polars-style offset, length to Python's start_index, end_index the following logic should apply consistently everywhere:

# Signed arithmetic (allows negatives).
start_idx = len(s) + offset if offset < 0 else offset
stop_idx = start_idx + length

# Clamp negatives / out-of-bounds.
def clamp(x, lo, hi): return max(lo, min(x, hi))
start_idx = clamp(start_idx, 0, len(s))
stop_idx = clamp(stop_idx, 0, len(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-ops Area: operations accepted Ready for implementation P-medium Priority: medium
Projects
Archived in project
Development

Successfully merging a pull request may close this issue.

1 participant