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

ENH: Support side='both' in np.searchsorted to return a pair of arrays #26448

Open
FreddieWitherden opened this issue May 15, 2024 · 0 comments

Comments

@FreddieWitherden
Copy link

FreddieWitherden commented May 15, 2024

Proposed new feature or change:

It would be nice if np.searchsorted could have an option to return both the left and right insertion indices. This change would be backwards compatible and roughly functionally equivalent to:

def searchsorted(a, v, side='left', sorter=None):
    if side == 'both':
        l = np.searchsorted(a, v, side='left', sorter=sorter)
        r = np.searchsorted(a, v, side='right', sorter=sorter)
        return l, r
    else:
        return np.searchsorted(a, v, side=side, sorter=sorter)

But, naturally, implemented so as to take advantage of the fact that the left and right indices are likely to be close, thus enabling some redundant searching to be avoided.

A use case for this is when you want to replace ranges of values in an array. From a real piece of code:

ls = np.searchsorted(con, mfrom, side='left')
le = np.searchsorted(con, mfrom, side='right')
for s, e, t in zip(ls, le, mto):
    con[s:e] = t

where there are a pair of calls to np.searchsorted which is then iterated over to yield ranges. This would be simplified under the new proposal to a single such call.

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

No branches or pull requests

1 participant