top_k¶
- top_k(x: array, k: int, /, *, axis: int = -1, mode: Literal['largest', 'smallest'] = 'largest') Tuple[array, array]¶
Returns the values and indices of the
klargest (or smallest) elements of an input arrayxalong a specified dimension.- Parameters:
x (array) – input array. Should have a real-valued data type.
k (int) – number of elements to find. Must be a nonnegative integer value.
axis (int) – axis along which to search. A valid axis must be an integer on the interval
[-N, N), whereNis the number of axes inx. If an axis is specified as a negative integer, the function must determine the axis along which to perform the operation by counting backward from the last axis (where-1refers to the last axis). If provided an invalid axis, the function must raise an exception. Default:-1.mode (Literal['largest', 'smallest']) –
search mode. Must be one of the following modes:
'largest': return theklargest elements.'smallest': return theksmallest elements.
Default:
'largest'.
- Returns:
out (Tuple[array, array]) – a namedtuple
(values, indices)whosefirst element must have the field name
valuesand must be an array containing theklargest (or smallest) elements ofx. The array must have the same data type asxand must have the same rank (number of dimensions) and shape asx, except for the axis specified byaxiswhich must have sizek.second element must have the field name
indicesand must be an array containing indices ofxthat result invalues. The array must have the same shape asvaluesand must have the default array index data type.
Notes
If
kexceeds the number of elements along the axis specified byaxis, behavior is left unspecified and thus implementation-dependent. Conforming implementations may choose, e.g., to raise an exception or return all elements.The order of the returned values and indices is left unspecified and thus implementation-dependent. Conforming implementations may return sorted or unsorted values.
The returned indices may maintain the relative order of
xvalues which compare as equal (i.e., the relative order ofxvalues which compare as equal is implementation-dependent).For input arrays containing
NaNvalues, behavior is left unspecified and thus implementation-dependent. Conforming implementations may choose to omitNaNvalues, sortNaNvalues to either end, or return unstable results.Conforming implementations may support complex numbers; however, inequality comparison of complex numbers is unspecified and thus implementation-dependent (see Complex Number Ordering).