If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the n highest elements are:

(-avgDists).argsort()[:n]

Another way to reason about this, as mentioned in the comments, is to observe that the big elements are coming last in the argsort. So, you can read from the tail of the argsort to find the n highest elements:

avgDists.argsort()[::-1][:n]

Both methods are O(n log n) in time complexity, because the argsort call is the dominant term here. But the second approach has a nice advantage: it replaces an O(n) negation of the array with an O(1) slice. If you're working with small arrays inside loops then you may get some performance gains from avoiding that negation, and if you're working with huge arrays then you can save on memory usage because the negation creates a copy of the entire array.

Note that these methods do not always give equivalent results: if a stable sort implementation is requested to argsort, e.g. by passing the keyword argument kind='mergesort', then the first strategy will preserve the sorting stability, but the second strategy will break stability (i.e. the positions of equal items will get reversed).

Example timings:

Using a small array of 100 floats and a length 30 tail, the view method was about 15% faster

>>> avgDists = np.random.rand(100)
>>> n = 30
>>> timeit (-avgDists).argsort()[:n]
1.93 µs ± 6.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
1.64 µs ± 3.39 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
1.64 µs ± 3.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

For larger arrays, the argsort is dominant and there is no significant timing difference

>>> avgDists = np.random.rand(1000)
>>> n = 300
>>> timeit (-avgDists).argsort()[:n]
21.9 µs ± 51.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
21.7 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
21.9 µs ± 37.1 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Please note that the comment from nedim below is incorrect. Whether to truncate before or after reversing makes no difference in efficiency, since both of these operations are only striding a view of the array differently and not actually copying data.

Answer from wim on Stack Overflow
Top answer
1 of 10
368

If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the n highest elements are:

(-avgDists).argsort()[:n]

Another way to reason about this, as mentioned in the comments, is to observe that the big elements are coming last in the argsort. So, you can read from the tail of the argsort to find the n highest elements:

avgDists.argsort()[::-1][:n]

Both methods are O(n log n) in time complexity, because the argsort call is the dominant term here. But the second approach has a nice advantage: it replaces an O(n) negation of the array with an O(1) slice. If you're working with small arrays inside loops then you may get some performance gains from avoiding that negation, and if you're working with huge arrays then you can save on memory usage because the negation creates a copy of the entire array.

Note that these methods do not always give equivalent results: if a stable sort implementation is requested to argsort, e.g. by passing the keyword argument kind='mergesort', then the first strategy will preserve the sorting stability, but the second strategy will break stability (i.e. the positions of equal items will get reversed).

Example timings:

Using a small array of 100 floats and a length 30 tail, the view method was about 15% faster

>>> avgDists = np.random.rand(100)
>>> n = 30
>>> timeit (-avgDists).argsort()[:n]
1.93 µs ± 6.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
1.64 µs ± 3.39 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
1.64 µs ± 3.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

For larger arrays, the argsort is dominant and there is no significant timing difference

>>> avgDists = np.random.rand(1000)
>>> n = 300
>>> timeit (-avgDists).argsort()[:n]
21.9 µs ± 51.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
21.7 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
21.9 µs ± 37.1 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Please note that the comment from nedim below is incorrect. Whether to truncate before or after reversing makes no difference in efficiency, since both of these operations are only striding a view of the array differently and not actually copying data.

2 of 10
98

Just like Python, in that [::-1] reverses the array returned by argsort() and [:n] gives that last n elements:

>>> avgDists=np.array([1, 8, 6, 9, 4])
>>> n=3
>>> ids = avgDists.argsort()[::-1][:n]
>>> ids
array([3, 1, 2])

The advantage of this method is that ids is a view of avgDists:

>>> ids.flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

(The 'OWNDATA' being False indicates this is a view, not a copy)

Another way to do this is something like:

(-avgDists).argsort()[:n]

The problem is that the way this works is to create negative of each element in the array:

>>> (-avgDists)
array([-1, -8, -6, -9, -4])

ANd creates a copy to do so:

>>> (-avgDists_n).flags['OWNDATA']
True

So if you time each, with this very small data set:

>>> import timeit
>>> timeit.timeit('(-avgDists).argsort()[:3]', setup="from __main__ import avgDists")
4.2879798610229045
>>> timeit.timeit('avgDists.argsort()[::-1][:3]', setup="from __main__ import avgDists")
2.8372560259886086

The view method is substantially faster (and uses 1/2 the memory...)

🌐
GeeksforGeeks
geeksforgeeks.org › numpy › how-to-use-numpy-argsort-in-descending-order-in-python
How to use numpy.argsort in Descending order in Python - GeeksforGeeks
July 23, 2025 - In this example, we are negating the NumPy Array to sort it in descending order using numy.argsort(). Here, we will use argsort() to get the indices that would sort the original array in ascending order.
🌐
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]])
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to use numpy argsort() in python
How to Use NumPy Argsort() in Python - Spark By {Examples}
March 27, 2024 - You are using numpy.argsort() to get the indices that would sort the input array in ascending order and then reversing these indices to obtain the descending order.
🌐
IncludeHelp
includehelp.com › python › is-it-possible-to-use-numpy-argsort-in-descending-order.aspx
Python - Is it possible to use numpy.argsort() in descending order?
May 25, 2023 - To use the numpy.argsort() method in descending order in Python, if we negate an array, the lowest elements become the highest elements and the highest elements become the lowest elements.
🌐
Codegive
codegive.com › blog › numpy_argsort_descending_order.php
Numpy argsort descending order
When axis is specified, argsort returns an array of indices with the same shape as the input, where each slice along the specified axis is sorted. For descending order in multi-dimensional arrays, the "negating the array" method (np.argsort(-arr, axis=X)) is often the most straightforward and ...
🌐
Vultr Docs
docs.vultr.com › python › third-party › numpy › argsort
Python Numpy argsort() - Sort Array Indices | Vultr Docs
November 11, 2024 - features = np.array([0.1, 0.6, 0.2, 0.8]) influential_features_indices = features.argsort()[::-1] print(influential_features_indices) Explain Code · Sorting the indices in descending order allows identifying the most influential features, which ...
Find elsewhere
🌐
Codecademy
codecademy.com › article › sorting-and-unary-operations-in-num-py
Sorting and Unary Operations in NumPy | Codecademy
By default, it sorts an array of numbers in ascending order. While direct sorting in descending order isn’t available through this function, it can be achieved by sorting in ascending order and then reversing the result.
🌐
Bobby Hadz
bobbyhadz.com › blog › using-numpy-argsort-in-descending-order-in-python
How to use numpy.argsort in Descending order in Python | bobbyhadz
April 11, 2024 - To be able to use numpy.argsort() in descending order, we negated the array by prefixing it with a minus -.
🌐
Finxter
blog.finxter.com › np-argsort
np.argsort() — A Simpe Illustrated Guide – Be on the Right Side of Change
In this basic example, we use the numpy.argsort() function to return the index of the sorted input array (in an ascending order) and then index the sorted array using the output. We can also return the index that sorts the input array in a descending order using the [::-1] reverse trick.
🌐
Python Guides
pythonguides.com › python-numpy-argsort
How To Use Np.argsort In Descending Order In Python
May 16, 2025 - While I was working on a data analysis ... highest-to-lowest values. In Python, NumPy’s argsort() function is perfect for this task, but by default, it sorts in ascending order....
🌐
JAX Documentation
docs.jax.dev › en › latest › _autosummary › jax.numpy.argsort.html
jax.numpy.argsort — JAX documentation
JAX implementation of numpy.argsort(). ... specifying whether a stable sort should be used. Default=True. descending (bool) – boolean specifying whether to sort in descending order....
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.sort.html
numpy.sort — NumPy v2.5.dev0 Manual
argsort · Indirect sort. lexsort · Indirect stable sort on multiple keys. searchsorted · Find elements in a sorted array. partition · Partial sort. Notes · The various sorting algorithms are characterized by their average speed, worst case performance, work space size, and whether they ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-argsort-in-python
numpy.argsort() in Python - GeeksforGeeks
July 11, 2025 - import numpy as np a = np.array([[2, 0, 1], [5, 4, 3]]) print("Axis 0:\n", np.argsort(a, axis=0)) print("Axis 1:\n", np.argsort(a, axis=1)) ... Axis 0 (columns): The values in each column are compared top-to-bottom. Axis 1 (rows): The values in each row are compared left-to-right. Example 2: This example finds the indices of the two largest elements in a NumPy array and retrieves their values in descending order.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.argsort.html
numpy.argsort — NumPy v2.4 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]])
🌐
Reddit
reddit.com › r/learnpython › problem with sorting in descending order
r/learnpython on Reddit: Problem with sorting in descending order
October 6, 2023 -

Hi, I am trying to sort in descending order in jupyter notebook

I tried from:StackExchange

import numpy as np #import numpy
games = np.array(['FIFA 2020','Red Dead Redemption','Fallout','GTA','NBA 2018','Need For Speed'])
print(games)
print("1",np.sort(games))
games = np.sort(games)
np.sort(games, order='descending')

But I am getting the error

ValueError: Cannot specify order when the array has no fields. 

Somebody, please guide me.

Zulfi.

Top answer
1 of 2
3
I think you are misunderstanding the order parameter. It doesn't do what you seem to think it does: >>> import numpy as np >>> help(np.sort) Help on _ArrayFunctionDispatcher in module numpy: sort(a, axis=-1, kind=None, order=None) Return a sorted copy of an array. Parameters ---------- ... 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. So order requires your array to have pre-defined "fields", whose members you pass in as order in the order you'd like them sorted according to. "descending" is obviously not a "field" of your array, hence it's not working. Note that despite ascending-order sorting seeming to work in your sample code, if you specify the order as such, you get the same error: >>> import numpy as np >>> games = np.array(['FIFA 2020','Red Dead Redemption','Fallout','GTA','NBA 2018','Need For Speed']) >>> np.sort(games, order='ascending') Traceback (most recent call last): ... ValueError: Cannot specify order when the array has no fields. Looking into this, it seems numpy.sort actually doesn't support descending order. So to achieve the same, just sort in ascending order, then slice in reverse: >>> np.sort(games)[::-1] array(['Red Dead Redemption', 'Need For Speed', 'NBA 2018', 'GTA', 'Fallout', 'FIFA 2020'], dtype='
2 of 2
3
Do you need numpy here? Seems overkill. games = ['FIFA 2020','Red Dead Redemption','Fallout','GTA','NBA 2018','Need For Speed'] sorted(games, reverse=True)
🌐
PyTorch
docs.pytorch.org › reference api › torch.argsort
torch.argsort — PyTorch 2.11 documentation
January 1, 2023 - descending (bool, optional) – controls the sorting order (ascending or descending) Keyword Arguments: stable (bool, optional) – controls the relative order of equivalent elements · Example: >>> a = torch.randn(4, 4) >>> a tensor([[ 0.0785, ...
🌐
Like Geeks
likegeeks.com › home › python › numpy › sorting numpy arrays: a comprehensive guide
Sorting NumPy Arrays: A Comprehensive Guide
July 6, 2024 - Here, we used a slicing technique [::-1] to reverse the sorted array. This returns the array in descending order. To sort a NumPy structured array by multiple columns, you can pass the column names you want to sort to the order parameter of ...
🌐
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 - argsort() returns the indices that would sort that column. So we use these indices to reorder the entire array. ... Notice how the rows have been rearranged based on the values in the second column.