numpy.top_k#
- numpy.top_k(a, k, /, *, axis=-1, mode='largest', sorted=True)[source]#
Returns the
klargest or smallest elements and their indices along an axis.A tuple of
(values, indices)is returned, wherevaluesandindicesare the values and indices, respectively, of the largest/smallest elements of each row of the input array in the givenaxis.- Parameters:
- a: array_like
The source array
- k: int
The number of largest/smallest elements to return.
kmust be a non-negative integer and within indexable range specified byaxis.- axis: int, optional
Axis along which to find the largest/smallest elements. The default is -1 (the last axis).
- mode: {“largest”, “smallest”}, optional
If “largest”, the largest elements are returned. If “smallest”, the smallest elements are returned. The default is “largest”.
Similarly to sorts, NaN values are pushed to the end and therefore only present in the output if they are among the top
kvalues, regardless of the value ofmode.- sorted: bool, optional
If True, the top
kelements are returned in sorted order. If False, sorted order is not guaranteed. The default is True.
- Returns:
- tuple_of_array: tuple
The output tuple of
(topk_values, topk_indices), wheretopk_valuesare the topkvalues andtopk_indicesare the corresponding indices. Both arrays are of the shape of the input array with the dimension alongaxisreplaced byk.
See also
argpartitionIndirect partition.
sortFull sorting.
Notes
The returned indices are not guaranteed to be stable, i.e., the order of the returned indices for any duplicate values is not guaranteed to be the same as their order in the input array. This is the case regardless of the value of the
sortedparameter.Examples
>>> a = np.array([[1,2,3,4,5], [5,4,3,2,1]]) >>> np.top_k(a, 2) (array([[5, 4], [5, 4]]), array([[4, 3], [0, 1]])) >>> np.top_k(a, 2, axis=0) (array([[5, 4, 3, 4, 5], [1, 2, 3, 2, 1]]), array([[1, 1, 0, 0, 0], [0, 0, 1, 1, 1]])) >>> np.top_k(a, 2, axis=1, mode="smallest") (array([[1, 2], [1, 2]]), array([[0, 1], [4, 3]])) >>> np.top_k(np.array([1., 2., 3., np.nan]), 2) (array([3., 2.]), array([2, 1]))