Skip to content

ENH: new function replace #992

Open

Description

@lucascolley

From https://hackmd.io/zn5bvdZTQIeJmb3RW1B-8g?both#Updates-from-the-sparse-array-ecosystem-Willow, @willow-ahrens suggested an xp.replace(array, old, new) function, which could have the agnostic implementation xp.where(xp.equals(...), old, new ).

@willow-ahrens if you'd like to work on this, we have contributor docs at https://data-apis.org/array-api-extra/contributing.html.

Activity

  1. kgryte commented on Sep 21, 2026

    @kgryte

    Bikeshed: might be worthwhile considering the current constellation of names among various array libraries and whether we want to introduce new vocabulary or build on existing vocabulary. E.g., NumPy already has fill, so fill_equal could be an option.

    Additionally, the proposed operation is a functional equivalent to

    x[x==old] = new

    which is already supported by the standard vis-a-vis boolean indexing. In principle, one could have a dedicated kernel for this operation, thus avoiding the intermediate boolean array, but there is a question whether this API is actually needed given support for boolean indexing.

  2. rgommers commented on Oct 29, 2026

    @rgommers
    Member

    Additionally, the proposed operation is a functional equivalent to x[x==old] = new

    Kinda but not really, since that doesn't work with JAX or other immutable implementations. The more generic equivalent is where(x == old, new, x), as in the issue description.

    I think it makes sense to add replace to array-api-extra, probably backed by an xp.where-based generic implementation. It provides:

    1. A cleaner API than the where equivalent,
    2. If implemented directly in array libraries with an optimized implementation that avoids constructing the boolean intermediate array, better eager performance

    Once (1) is in, we can use it immediately in scipy, since we vendor array_api_extra. There are probably a couple of dozen places where it can be used. Doing that will give a better feel for whether (2) is worth doing.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions