Skip to content

Replace interp1d(kind='zero') with np.searchsorted for better performance #1

Description

@SaFE-APIOpt

func = interp1d(xp, yp, kind='zero', fill_value='extrapolate', assume_sorted=False)

Hi, thank you for the great work!
In the following code:

func = interp1d(xp, yp, kind='zero', fill_value='extrapolate', assume_sorted=False)
return np.where(np.asanyarray(x) < xmin, left, func(x))

Suggested Optimization

ix = np.searchsorted(xp, x, side='right') - 1
func = lambda x: yp[ix]

This replacement removes the need for interp1d, avoids Python-level function dispatch, and leverages NumPy’s highly optimized searchsorted for efficient zero-order hold interpolation.
This approach is not only faster but also more memory-efficient, and still preserves the original extrapolation behavior using np.where.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions