Python基本函数:np.argsort()

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]]              	
发布了36 篇原创文章 · 获赞 5 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_40520596/article/details/102808626