numpy.argpartition(a, kth, axis=-1, kind='introselect', order=None)
The NumPy argpatition function performs an indirect partition along the given axis using the algorithm specified by the kind
keyword. It returns an array of indices of the same shape as a that index data along the given axis in partitioned order.
Arguments | Type | Description |
---|---|---|
c | array_like or poly1d object | The input polynomials to be multiplied |
kth | integer or sequence of integers | Element index to partition by. The k-th element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all of them into their sorted position at once. |
axis | integer or None | (Optional.) Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used. |
kind | {'introselect'} | (Optional.) Selection algorithm. Default is 'introselect' . |
order | string or list of strings | (Optional.) When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. |
The following table shows the return value of the function:
Type | Description | |
---|---|---|
Return Value | index_array : ndarray, int | Array of indices that partition a along the specified axis. If a is one-dimensional, a[index_array] yields a partitioned a. More generally, np.take_along_axis(a, index_array, axis=a) always yields the partitioned a, irrespective of dimensionality. |
Related: See partition
for notes on the different selection algorithms.
Let’s dive into some examples to show how the function is used in practice:
Examples
One-dimensional array:
import numpy as np x = np.array([3, 4, 2, 1]) print(x[np.argpartition(x, 3)]) # [2 1 3 4] print(x[np.argpartition(x, (1, 3))]) # [1 2 3 4]
Multi-dimensional array:
import numpy as np x = np.array([3, 4, 2, 1]) print(x[np.argpartition(x, 3)]) # [2 1 3 4] print(x[np.argpartition(x, (1, 3))]) # [1 2 3 4] x = [3, 4, 2, 1] print(np.array(x)[np.argpartition(x, 3)]) # [2 1 3 4]
Any master coder has a “hands-on” mentality with a bias towards action. Try it yourself—play with the function in the following interactive code shell:
Exercise: Change the parameters of your polynomials and print them without the comparisons. Do you understand where they come from?
Master NumPy—and become a data science pro: