numpy.argpartition#

numpy.argpartition(a,kth,axis=-1,kind='introselect',order=None)[source]#

Perform an indirect partition along the given axis using thealgorithm specified by thekind keyword. It returns an array ofindices of the same shape asa that index data along the givenaxis in partitioned order.

Parameters:
aarray_like

Array to sort.

kthint or sequence of ints

Element index to partition by. The k-th element will be in itsfinal sorted position and all smaller elements will be movedbefore it and all larger elements behind it. The order of allelements in the partitions is undefined. If provided with asequence of k-th it will partition all of them into their sortedposition at once.

Deprecated since version 1.22.0:Passing booleans as index is deprecated.

axisint or None, optional

Axis along which to sort. The default is -1 (the last axis). IfNone, the flattened array is used.

kind{‘introselect’}, optional

Selection algorithm. Default is ‘introselect’

orderstr or list of str, optional

Whena is an array with fields defined, this argumentspecifies which fields to compare first, second, etc. A singlefield can be specified as a string, and not all fields need bespecified, but unspecified fields will still be used, in theorder in which they come up in the dtype, to break ties.

Returns:
index_arrayndarray, int

Array of indices that partitiona along the specified axis.Ifa is one-dimensional,a[index_array] yields a partitioneda.More generally,np.take_along_axis(a,index_array,axis=axis)always yields the partitioneda, irrespective of dimensionality.

See also

partition

Describes partition algorithms used.

ndarray.partition

Inplace partition.

argsort

Full indirect sort.

take_along_axis

Applyindex_array from argpartition to an array as if by calling partition.

Notes

The returned indices are not guaranteed to be sorted according tothe values. Furthermore, the default selection algorithmintroselectis unstable, and hence the returned indices are not guaranteedto be the earliest/latest occurrence of the element.

argpartition works for real/complex inputs with nan values,seepartition for notes on the enhanced sort order anddifferent selection algorithms.

Examples

One dimensional array:

>>>importnumpyasnp>>>x=np.array([3,4,2,1])>>>x[np.argpartition(x,3)]array([2, 1, 3, 4]) # may vary>>>x[np.argpartition(x,(1,3))]array([1, 2, 3, 4]) # may vary
>>>x=[3,4,2,1]>>>np.array(x)[np.argpartition(x,3)]array([2, 1, 3, 4]) # may vary

Multi-dimensional array:

>>>x=np.array([[3,4,2],[1,3,1]])>>>index_array=np.argpartition(x,kth=1,axis=-1)>>># below is the same as np.partition(x, kth=1)>>>np.take_along_axis(x,index_array,axis=-1)array([[2, 3, 4],       [1, 1, 3]])
On this page