numpy.argsort() in PythonThe NumPy module provides a function argsort(), returns the indices which would sort an array. The NumPy module provides a function for performing an indirect sort along with the given axis with the help of the algorithm specified by the keyword. This function returns an array of indices of the same shape as 'a', which would sort the array. SyntaxParametersThese are the following parameters in numpy.argsort() function: a: array_like This parameter defines the source array which we want to sort. axis: int or None(optional) This parameter defines the axis along which the sorting is performed. By default, the axis is -1. If we set this parameter to None, the flattened array is used. kind: {'quicksort','mergesort','heapsort','stable'}(optional) This parameter defines the sorting algorithm. By default, the algorithm is quicksort. Both mergesort and stable are using time sort under the covers. The actual implementation will vary with the data type. The mergesort option is retained for backward compatibility. order: str or list of str(optional) If 'a' is an array with defined fields, this argument specifies which fields to compare first, second, etc. The single field can be specified as a string, and not all fields need to be specified. But unspecified fields will still use, in the order in which they come up in the dtype, to break the ties. Returns: index_array: ndarray, intThis function returns an array of indices which sort 'a' along with the specified axis. If 'a' is 1-D, a[index_array] yields a sorted 'a'. More generally, np.take_along_axis(arr1, index_array, axis=axis) always yields the sorted 'a', irrespective of dimensionality. Example 1: np.argsort()In the above code
In the output, a ndarray has been shown that contains the indices(indicate the position of the element for the sorted array) and dtype. Output: array([456, 11, 63]) array([1, 2, 0], dtype=int64) Example 2: For 2-D array( sorts along first axis (down))Output: array([[0, 1], [1, 0]], dtype=int64) Example 3: For 2-D array(alternative of axis=0)In the above code
In the output, a 2-D array with sorted elements has been shown. Output: array([[0, 2], [3, 5]]) Example 4: For 2-D array( sorts along last axis (across))Output: array([[0, 1], [1, 0]], dtype=int64) Example 5: For 2-D array(alternative of axis=1)Output: array([[0, 2], [3, 5]]) Example 6: For N-D arrayOutput: (array([0, 1, 1, 0], dtype=int64), array([0, 1, 0, 1], dtype=int64)) array([0, 2, 3, 5]) In the above code
In the output, an N-D array with sorted elements has been shown. Example 7: Sorting with keysOutput: array([(0, 5), (3, 2)], dtype=[('x', '<i4'), ('y', '<i4')]) array([0, 1], dtype=int64) array([1, 0], dtype=int64) In the above code
In the output, a sorted array has been shown with dtype=[('x', '<i4'), ('y', '<i4')] Next Topicnumpy.transpose() |