nearest_index#

rojak.core.indexing.nearest_index(coordinate, values, *, tie_break_convention=NearestTieBreakConvention.UPPER)[source]#

Compute the index of the value in coordinate that is closest to each of values

coordinate does not need to be regularly spaced or sorted. It is sorted once and each value is located with a binary search, so it costs \(O((n + m) \log m)\) for \(n\) values and \(m\) coordinate values.

Ties (i.e. values exactly halfway between two coordinate values) are broken according to tie_break_convention. With NearestTieBreakConvention.UPPER (the default), ties are broken towards the larger coordinate value, consistent with pandas.Index.get_indexer() and xarray.DataArray.sel() with method="nearest". With NearestTieBreakConvention.LOWER, ties are broken towards the smaller coordinate value. Values outside of the range of coordinate map to the index of its minimum or maximum. Missing values (NaN or NaT) map to index 0.

Parameters:
  • coordinate (NDArray) – 1D array which is to be indexed into

  • values (NDArray) – Values to find the closest index in coordinate of

  • tie_break_convention (NearestTieBreakConvention) – Convention used to break ties. Defaults to NearestTieBreakConvention.UPPER

Returns:

Array of the same shape as values with the index in coordinate that each value is closest to

Return type:

NDArray[np.intp]

>>> nearest_index(np.array([0.0, 10.0, 20.0]), np.array([-5.0, 4.0, 6.0, 25.0]))
array([0, 0, 1, 2])
>>> nearest_index(np.array([20.0, 10.0, 0.0]), np.array([-5.0, 4.0, 6.0, 25.0]))
array([2, 2, 1, 0])
>>> nearest_index(np.array([10.0, 0.0, 30.0, 20.0]), np.array([1.0, 12.0, 27.0]))
array([1, 0, 2])

Ties are broken towards the larger coordinate value

>>> nearest_index(np.array([0.0, 10.0, 20.0]), np.array([5.0, 15.0]))
array([1, 2])
>>> nearest_index(np.array([20.0, 10.0, 0.0]), np.array([5.0, 15.0]))
array([1, 0])