searchsorted#

named_arrays.searchsorted(a, v, axis=None, side='left', sorter=None)#

Thin wrapper around numpy.searchsorted().

Find the index along axis where each element of v would have to be inserted to leave a sorted.

This function adds an axis argument, which lets a carry axes besides the one it is sorted along, where numpy.searchsorted() takes a one-dimensional a only. Those other axes are batch axes, and each is searched independently of the rest.

Parameters:
  • a (AbstractArray) – The sorted array to search. It must be increasing along axis, which is not checked, exactly as numpy.searchsorted() does not check it.

  • v (float | Quantity | AbstractArray) – The values to find the insertion points of.

  • axis (None | str) – The logical axis along which a is sorted. If None, a must have exactly one axis.

  • side (Literal['left', 'right']) – Which end of a run of equal values to return the index of. "left" gives the first such index and "right" the one past the last.

  • sorter (None | AbstractArray) – The indices along axis which sort a, as numpy.argsort() returns them. If None, a is taken to be sorted already.

Returns:

  • The indices into axis, carrying the axes of v broadcast

  • against the batch axes of a.

Return type:

AbstractArray

See also

numpy.searchsorted()

The function this one wraps.

digitize()

Which bin each value falls into, on the same machinery.

Examples

Find where two spectral lines fall in a wavelength grid.

import numpy as np
import astropy.units as u
import named_arrays as na

grid = na.linspace(100, 200, axis="wavelength", num=6) * u.AA

line = na.ScalarArray(
    ndarray=np.array([117, 185]) * u.AA,
    axes=("line",),
)

na.searchsorted(grid, line, axis="wavelength")
ScalarArray(
    ndarray=[1, 5],
    shape={'line': 2},
)