Python基本函数:np.argsort()

格式:np.argsort(a)
注意:返回的是元素值从小到大排序后的索引值的数组

一、函数说明

argsort(a, axis=-1, kind='quicksort', order=None)
    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.

  返回排序后的索引值的数组!若还是没看明白,下面则是例子来辅助理解。
 

二、函数用法

1、一维数组

In :       	a = np.array([3,1,2,1,3,5])
Out: 		[3,1,2,1,3,5]

In : 		b = np.argsort(a)                        # 对a按升序排列        
Out: 		[1 3 2 0 4 5]      

In : 		b = np.argsort(-a)                       # 对a按降序排列        
Out: 		[5 0 4 2 1 3]               	

2、二维数组

In :       	a = np.array([[0, 3, 5], [2, 2, 2]])
Out: 		[[0, 3, 5]
			 [2, 2, 2]]

In : 		b = np.argsort(a, axis=0)                # 对a按列进行排序              
Out: 		[[0 1 1]
 			 [1 0 0]]     

In : 		b = np.argsort(a, axis=1)                # 对a按行进行排序              
Out: 		[[0 1 2]
 			 [0 1 2]]              	
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐