Python-numpy.argsort

numpy.argsort(a, axis=-1, kind='quicksort', order=None)[source]

Returns the indices that would sort an array.

Perform an indirect sort 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 sorted order.

Parameters:

a : array_like

Array to sort.

axis : int or None, optional

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

kind : {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional

Sorting algorithm.

order : str or list of str, 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.

Returns:

index_array : ndarray, int

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

 numpy.argsort(a,axis=-1,kind='quicksort',order=none)
返回将对数组排序的索引。
使用kind关键字指定的算法沿给定轴执行间接排序。它返回一个与该索引数据形状相同的索引数组,并沿给定轴按排序顺序排列。

参数:

a : array_like要排序的数组。

axis : int或none,可选

要排序的Axis 。默认值为-1(最后一个Axis )。如果没有,则使用扁平数组。

kind : {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, 可选,排序算法。

order : str或str列表,可选

当a是定义了字段的数组时,此参数指定要比较的第一个、第二个等字段。可以将单个字段指定为字符串,并且不需要指定所有字段,但仍将使用未指定的字段,按它们在数据类型中的出现顺序来断开关系。

返回:

index_array:ndarray,int
沿指定轴排序的索引数组。如果a是一维的,则[index_array]生成排序后的a。更一般地说,np.take_along_axis(a,index_array,axis=a)获取排序后的a,与维数无关。

例如:

一维数组:

>>>

>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])

二维数组:

>>>

>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
       [2, 2]])

>>>

>>> np.argsort(x, axis=0)  # sorts along first axis (down)
array([[0, 1],
       [1, 0]])

>>>

>>> np.argsort(x, axis=1)  # sorts along last axis (across)
array([[0, 1],
       [0, 1]])

n维数组的排序元素的索引:

>>>

>>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
>>> ind
(array([0, 1, 1, 0]), array([0, 0, 1, 1]))
>>> x[ind]  # same as np.sort(x, axis=None)
array([0, 2, 2, 3])

使用键排序:

>>>

>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
array([(1, 0), (0, 1)],
      dtype=[('x', '<i4'), ('y', '<i4')])

>>>

>>> np.argsort(x, order=('x','y'))
array([1, 0])

>>>

>>> np.argsort(x, order=('y','x'))
array([0, 1])

翻译地址:https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html

猜你喜欢

转载自blog.csdn.net/weixin_40446557/article/details/87938947