📜  np argmin top n - Python (1)

📅  最后修改于: 2023-12-03 15:17:58.871000             🧑  作者: Mango

np.argmin() and top-n in Python

In Python, np.argmin() function is used to get the minimum value along a particular axis from an array. The np.argmin() function returns the indices of the minimum values in the array. If there are multiple occurrences of minimum values, it returns the index of the first occurrence.

Syntax:
np.argmin(a, axis=None, out=None)
Parameters:
  • a : array_like: Input data.
  • axis : int, optional: Axis along which the minimum value is computed. Default is None, which means the index of the minimum value in the flattened array is returned.
  • out : ndarray, optional: Alternative output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary.
Return:
  • min_index : ndarray: ndarray of indices of the minimum element of the array in along the specified axis.
Example:
import numpy as np
a = np.array([[10, 50, 30], [60, 20, 40]])
print(np.argmin(a))

Output:

3

In this example, np.argmin() function returns 3 as the minimum value in the flattened array is 10.

If you want to get the index of n smallest values in a numpy array, you can use np.argpartition() function. It returns the indices that would partition the array into groups based on the top n smallest values indices.

Syntax:
np.argpartition(a, kth, axis=-1, kind='introselect', order=None)
Parameters:
  • a : array_like: Input array.
  • kth : int or sequence of ints: The k-th smallest value to partition the array around. If array has shape (n,m)) and axis = None, kth must be in [0, n*m - 1]. If kth is an array of ints, then a partition is made at all of those indices. Negative indices are not supported.
  • axis : int or None or tuple of ints or None, optional: Axis along which to sort. Default is -1.
  • kind : {'introselect'}, optional: Selection algorithm. Default is 'introselect'.
  • order : str or list of str or None, 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. Not all fields need to be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
Return:
  • indices : ndarray: When axis is None, indices is a 1-D array of indices which indicate the partitioned order of the array. When axis is an integer, the same shape as self is returned, but with the corresponding axis replaced with the indices that would sort each subarray.
Example:
import numpy as np
a = np.array([12, 3, 56, 32, 85, 4, 30, 11])
n = 3
print(np.argpartition(a, n)[:n])

Output:

[1 7 5]

In this example, np.argpartition() function returns the indices of the 3 smallest elements in the array.