numpy
  1. numpy-numpyargsort

numpy.argsort()

The numpy.argsort() function performs an indirect sort on input array along the given axis and returns an array of indices of the data in sorted order. The method used for sorting is QuickSort.

Syntax

numpy.argsort(a, axis=-1, kind=None, order=None)

  • a : Array to be sorted
  • axis : Axis along which sorting should be perform.Default -1
  • kind : Sorting algorithm. Default QuickSort
  • order : If the input contains fields on which to be sorted, then it is used to specify field names.

Example

import numpy as np

arr = np.array([2, 45, 89, 1, 10, 8])

indices = np.argsort(arr)

print(indices)

Output:

[3 0 5 4 1 2]

In the above example, we create an array of integers and then find the indices that would sort the array in ascending order using numpy.argsort() function.

Explanation

The numpy.argsort() function performs an indirect sort on an array and returns a new array of indices that would sort the input array along the specified axis. By default, the sorting algorithm used is QuickSort.

Use

The numpy.argsort() function is used for tasks that require sorting, while also preserving the original index order of the elements. It is commonly used to extract the index of the minimum or maximum element of an array.

Important Points

  • The returned array of indices contains integers that indicate the position of the sorted elements of the input array.
  • If the input array contains elements of different data types, they will be sorted according to their respective types.
  • In case of multi-dimensional arrays, the axis parameter specifies the axis along which the sort should be performed.

Summary

The numpy.argsort() function performs an indirect sort on an array along the specified axis and returns an array of indices of the data in sorted order. It is commonly used to extract the index of the minimum or maximum element of an array. This function is incredibly useful when dealing with large datasets where sorting needs to be performed on more than one dimension.

Published on: