nearest_index#
- rojak.core.indexing.nearest_index(coordinate, values, *, tie_break_convention=NearestTieBreakConvention.UPPER)[source]#
Compute the index of the value in
coordinatethat is closest to each ofvaluescoordinatedoes 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. WithNearestTieBreakConvention.UPPER(the default), ties are broken towards the larger coordinate value, consistent withpandas.Index.get_indexer()andxarray.DataArray.sel()withmethod="nearest". WithNearestTieBreakConvention.LOWER, ties are broken towards the smaller coordinate value. Values outside of the range ofcoordinatemap to the index of its minimum or maximum. Missing values (NaNorNaT) map to index0.- Parameters:
coordinate (NDArray) – 1D array which is to be indexed into
values (NDArray) – Values to find the closest index in
coordinateoftie_break_convention (NearestTieBreakConvention) – Convention used to break ties. Defaults to
NearestTieBreakConvention.UPPER
- Returns:
Array of the same shape as
valueswith the index incoordinatethat 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])