Either tell python to sort only on the first item

sorted(ls, key=lambda t: t[0])

Or convert the whole thing to a structured numpy array and ask numpy to sort it

ls_arr = np.array(ls, dtype=[('my_val', float), ('my_arr', float, 2)])
ls_arr.sort()

This second option only works if the arrays are always the same length.

Answer from Eric on Stack Overflow
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ stable โ€บ reference โ€บ generated โ€บ numpy.argsort.html
numpy.argsort โ€” NumPy v2.4 Manual
>>> ind = np.argsort(x, axis=1) # sorts along last axis (across) >>> ind array([[0, 1], [0, 1]]) >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1) array([[0, 3], [2, 2]])
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ generated โ€บ numpy.argsort.html
numpy.argsort โ€” NumPy v2.1 Manual
>>> ind = np.argsort(x, axis=0) # sorts along first axis (down) >>> ind array([[0, 1], [1, 0]]) >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0) array([[0, 2], [2, 3]])
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.2 โ€บ reference โ€บ generated โ€บ numpy.argsort.html
numpy.argsort โ€” NumPy v2.2 Manual
>>> ind = np.argsort(x, axis=0) # sorts along first axis (down) >>> ind array([[0, 1], [1, 0]]) >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0) array([[0, 2], [2, 3]])
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ numpy-argsort-in-python
numpy.argsort() in Python - GeeksforGeeks
April 25, 2025 - Input Array: A 2D NumPy array is created and displayed. Sorting along axis 0 (mergesort): np.argsort(a, kind='mergesort', axis=0) sorts the array along the columns (axis 0) using the mergesort algorithm and returns the indices of the sorted elements.
๐ŸŒ
NumPy
numpy.org โ€บ devdocs โ€บ reference โ€บ generated โ€บ numpy.argsort.html
numpy.argsort โ€” NumPy v2.5.dev0 Manual
>>> ind = np.argsort(x, axis=1) # sorts along last axis (across) >>> ind array([[0, 1], [0, 1]]) >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1) array([[0, 3], [2, 2]])
Find elsewhere
๐ŸŒ
Skytowner
skytowner.com โ€บ explore โ€บ numpy_argsort_method
NumPy | argsort method with Examples
A Numpy array containing the indices of the sorted copy of the input array. ... Our array x consists of three tuples, with the 1st element as the name, and the 2nd element as the age.
๐ŸŒ
SciPy
scipy.github.io โ€บ old-wiki โ€บ pages โ€บ argsort.html
argsort - SciPy wiki dump
1 >>> from numpy import * 2 >>> a = array([2,0,8,4,1]) 3 >>> ind = a.argsort() # indices of sorted array using quicksort (default) 4 >>> ind 5 array([1, 4, 0, 3, 2]) 6 >>> a[ind] # same effect as a.sort() 7 array([0, 1, 2, 4, 8]) 8 >>> ind = a.argsort(kind='merge') # algorithm options are 'quicksort', 'mergesort' and 'heapsort' 9 >>> a = array([[8,4,1],[2,0,9]]) 10 >>> ind = a.argsort(axis=0) # sorts on columns.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.3 โ€บ reference โ€บ generated โ€บ numpy.argsort.html
numpy.argsort โ€” NumPy v2.3 Manual
>>> ind = np.argsort(x, axis=0) # sorts along first axis (down) >>> ind array([[0, 1], [1, 0]]) >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0) array([[0, 2], [2, 3]])
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ numpy โ€บ methods โ€บ argsort
NumPy argsort()
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]
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.2 โ€บ reference โ€บ generated โ€บ numpy.ma.argsort.html
numpy.ma.argsort โ€” NumPy v2.2 Manual
>>> import numpy as np >>> a = np.ma.array([3,2,1], mask=[False, False, True]) >>> a masked_array(data=[3, 2, --], mask=[False, False, True], fill_value=999999) >>> a.argsort() array([1, 0, 2])
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.0 โ€บ reference โ€บ generated โ€บ numpy.argsort.html
numpy.argsort โ€” NumPy v2.0 Manual
>>> ind = np.argsort(x, axis=0) # sorts along first axis (down) >>> ind array([[0, 1], [1, 0]]) >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0) array([[0, 2], [2, 3]])
๐ŸŒ
Medium
medium.com โ€บ @whyamit404 โ€บ sorting-numpy-arrays-by-column-using-numpy-sort-c45a44660dcc
Sorting NumPy Arrays by Column Using numpy.sort() | by whyamit404 | Medium
February 26, 2025 - The trick is to pass a tuple of columns to lexsort(), where the last column in the tuple is the primary key for sorting. In this case, it sorts first by the second column, and if there are ties, it sorts by the first column.
Top answer
1 of 10
174

According to the documentation

Returns the indices that would sort an array.

  • 2 is the index of 0.0.
  • 3 is the index of 0.1.
  • 1 is the index of 1.41.
  • 0 is the index of 1.48.
2 of 10
51

[2, 3, 1, 0] indicates that the smallest element is at index 2, the next smallest at index 3, then index 1, then index 0.

There are a number of ways to get the result you are looking for:

import numpy as np
import scipy.stats as stats

def using_indexed_assignment(x):
    "https://stackoverflow.com/a/5284703/190597 (Sven Marnach)"
    result = np.empty(len(x), dtype=int)
    temp = x.argsort()
    result[temp] = np.arange(len(x))
    return result

def using_rankdata(x):
    return stats.rankdata(x)-1

def using_argsort_twice(x):
    "https://stackoverflow.com/a/6266510/190597 (k.rooijers)"
    return np.argsort(np.argsort(x))

def using_digitize(x):
    unique_vals, index = np.unique(x, return_inverse=True)
    return np.digitize(x, bins=unique_vals) - 1

For example,

In [72]: x = np.array([1.48,1.41,0.0,0.1])

In [73]: using_indexed_assignment(x)
Out[73]: array([3, 2, 0, 1])

This checks that they all produce the same result:

x = np.random.random(10**5)
expected = using_indexed_assignment(x)
for func in (using_argsort_twice, using_digitize, using_rankdata):
    assert np.allclose(expected, func(x))

These IPython %timeit benchmarks suggests for large arrays using_indexed_assignment is the fastest:

In [50]: x = np.random.random(10**5)
In [66]: %timeit using_indexed_assignment(x)
100 loops, best of 3: 9.32 ms per loop

In [70]: %timeit using_rankdata(x)
100 loops, best of 3: 10.6 ms per loop

In [56]: %timeit using_argsort_twice(x)
100 loops, best of 3: 16.2 ms per loop

In [59]: %timeit using_digitize(x)
10 loops, best of 3: 27 ms per loop

For small arrays, using_argsort_twice may be faster:

In [78]: x = np.random.random(10**2)

In [81]: %timeit using_argsort_twice(x)
100000 loops, best of 3: 3.45 ยตs per loop

In [79]: %timeit using_indexed_assignment(x)
100000 loops, best of 3: 4.78 ยตs per loop

In [80]: %timeit using_rankdata(x)
100000 loops, best of 3: 19 ยตs per loop

In [82]: %timeit using_digitize(x)
10000 loops, best of 3: 26.2 ยตs per loop

Note also that stats.rankdata gives you more control over how to handle elements of equal value.

๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ python โ€บ third-party โ€บ numpy โ€บ argsort
Python Numpy argsort() - Sort Array Indices | Vultr Docs
November 11, 2024 - Use the argsort() function to get sorted indices. ... import numpy as np data = np.array([10, 1, 5, 3, 8, 6]) sorted_indices = data.argsort() print(sorted_indices) Explain Code
๐ŸŒ
Iifx
iifx.dev โ€บ english โ€บ python
python - Descending Order Sorting with NumPy argsort: Simple & Effective
Use np.argsort() to get the indices for ascending order. Use np.flip() to reverse the order of these indices. import numpy as np arr = np.array([3, 1, 4, 1, 5, 9, 2, 6]) ascending_indices = np.argsort(arr) descending_indices = np.flip(ascen...