NumPy argsort()

The argsort() method in NumPy sorts the array elements in ascending order and returns indices of the sorted elements.

import numpy as np

array = np.array([10, 2, 9, -1])

# sort an array in ascending order # returns indices of the sorted array sortedIndices = np.argsort(array)
print('Index of sorted array:', sortedIndices) print('Sorted array:', array[sortedIndices]) # Output # Index of sorted array: [3 1 2 0] # Sorted array: [-1 2 9 10]

We can also sort an array from index using fancy indexing.


argsort() Syntax

The syntax of argsort() is:

numpy.argsort(array, axis, order, kind)

argsort() Arguments

The argsort() method takes four arguments:

  • array - array to be sorted
  • axis (optional) - axis along which the values are sorted
  • order (optional) - field to compare
  • kind (optional) - sorting algorithm

Notes:

  • By default, axis is -1, the array is sorted based on the last axis.
  • kind can be quicksort (default), mergesort, or heapsort.

argsort() Return Value

The argsort() method returns the indices that would sort an array.


Example 1: argsort() to Sort a Numerical Array

import numpy as np

array = np.array([10.20, 2.10, 9.9, -1.4])

# sort the array in ascending order sortedIndices= np.argsort(array)
print('Index of sorted array: ', sortedIndices) print('Sorted array: ', array[sortedIndices])

Output

Index of sorted array:  [3 1 2 0]
Sorted array:  [-1.4  2.1  9.9 10.2]

Example 2: argsort() to Sort a String Array

import numpy as np

array = np.array(['Apple', 'apple', 'Ball', 'Cat'])

# sort a string array based on their ASCII values
sortedIndices = np.argsort(array) print('Index of sorted array: ', sortedIndices) print('Sorted array: ',array[sortedIndices])

Output

Index of sorted array:  [0 2 3 1]
Sorted array:  ['Apple' 'Ball' 'Cat' 'apple']

Example 3: argsort() to Sort a Multidimensional Array

Multidimensional arrays are sorted based on the given axis.

import numpy as np

array = np.array(
    [[3, 10, 2], 
    [1, 5, 7], 
    [2, 7, 5]])

# sort column wise based on the axis -1 array2 = np.argsort(array) # flattens the given array and sorts the flattened array array3 = np.argsort(array, axis = None) # sort array row wise array4 = np.argsort(array, axis = 0)
print('Index of sorted array on last axis(-1): \n', array2) print('Index of a flattened sorted array: \n', array3) print('Index of sorted array on axis 0: \n', array4)

Output

Index of sorted array on last axis(-1): 
[[2 0 1]
 [0 1 2]
 [0 2 1]]
Index of a flattened sorted array: 
 [3 2 6 0 4 8 5 7 1]
Index of sorted array on axis 0: 
 [[1 1 0]
 [2 2 2]
 [0 0 1]]

When sorting on axis 0, rows are compared. The elements in the first column are sorted first followed by the second column and so on. All columns are sorted independently of each other.


Example 4: argsort() to Sort an Array With order Argument

import numpy as np

datatype = [('name', 'U7'), ('age', int), ('height', int)]
people = [
    ('Alice', 25, 170), 
    ('Bob', 30, 180), 
    ('Charlie', 35, 175)
]
array = np.array(people, dtype = datatype)

# sort the array based on height array2 = np.argsort(array, order = 'height')
print('Index of sorted array:\n', array2) print('Sorted array:\n', array[array2])

Output

Index of sorted array:
[0 2 1]
Sorted array:
 [('Alice', 25, 170) ('Charlie', 35, 175) ('Bob', 30, 180)]

Example 5: argsort() to Sort an Array With Multiple order Argument

import numpy as np

datatype = [('name', 'U7'), ('age', int), ('height', int)]
people = [
    ('Alice', 25, 170), 
    ('Bob', 30, 180), 
    ('Charlie', 35, 175),
    ('Dan', 40, 175),
    ('Eeyore', 25, 180)
]
array = np.array(people, dtype = datatype)

# sort the people array on the basis of height # if heights are equal, sort people on the basis of age array2 = np.argsort(array, order = ('height', 'age'))
print('Index of sorted array:\n',array2) print('Sorted array:\n',array[array2])

Output

Index of sorted array:
[0 2 3 4 1]
Sorted array:
 [('Alice', 25, 170) ('Charlie', 35, 175) ('Dan', 40, 175)
 ('Eeyore', 25, 180) ('Bob', 30, 180)]

The kind Argument

The kind argument is used in NumPy argsort() to specify the algorithm used for sorting. For example,

import numpy as np

array = np.array([10, 2, 9, 1])

# sort an array in ascending order by quicksort algorithm
array2 = np.argsort(array, kind = 'quicksort')

print('Index of sorted array:\n',array2)
print('Sorted array:\n',array[array2])

Output

Index of sorted array:
[3 1 2 0]
Sorted array:
 [ 1  2  9 10]

The kind argument can take several values, including,

  • quicksort (default): This is a fast algorithm that works well for most cases i.e. small and medium-sized arrays with random or uniformly distributed elements.
  • mergesort: This is a stable, recursive algorithm that works well for larger arrays with repeated elements.
  • heapsort: This is a slower, but guaranteed O(n log n) sorting algorithm that works well for smaller arrays with random or uniformly distributed elements

The kind argument has no direct impact on the output but it determines the performance of the method.


See also: Numpy.sort()