How to use numpy.argsort in Descending order in Python

Borislav Hadzhiev

Last updated: Apr 11, 2024

Reading timeยท5 min

- How to use numpy.argsort in Descending order in Python
- Using numpy.argsort() in descending order with a negative step
- How to use numpy.argsort in Descending order with numpy.flip()
- Using
`numpy.argsort()`

in descending order by multiplying by`-1`

**To use the numpy.argsort() method in descending order in Python, negate the
array before calling argsort().**

**When you negate the array, the lowest elements become the highest elements and
vice versa.**

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr.argsort()) # ๐๏ธ [1 0 2 3] # โ Using numpy.argsort() in descending order print((-arr).argsort()) # ๐๏ธ [3 2 0 1]`

The code for this article is available on GitHub

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

The method returns an array of indices of the same shape as the array along the given axis in sorted order.

By default, the `axis`

parameter is set to `-1`

, which means that the array is
sorted along the last axis.

To be able to use `numpy.argsort()`

in descending order, we negated the array by
prefixing it with a minus `-`

.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(-arr) # ๐๏ธ [-4 -1 -5 -7]`

When you negate the array, the lowest elements become the highest and vice versa, because the sign of each element is switched.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr.argsort()) # ๐๏ธ [1 0 2 3] # โ Using numpy.argsort() in descending order print((-arr).argsort()) # ๐๏ธ [3 2 0 1]`

The code for this article is available on GitHub

Array indexes are zero-based, so the first element in an array has an index of
`0`

and the last element has an index of `-1`

or `len(arr) - 1`

.

The largest element in the array has an index of `3`

and the second largest an
index of `2`

.

The smallest element in the array has an index of `1`

.

Make sure to wrap

`(-arr)`

in parentheses because we want to negate the array before calling `argsort()`

.If you need to select the indices of the highest N elements, use the following code sample.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr.argsort()) # ๐๏ธ [1 0 2 3] print((-arr).argsort()[:2]) # ๐๏ธ [3 2] print((-arr).argsort()[:3]) # ๐๏ธ [3 2 0] print((-arr).argsort()[:4]) # ๐๏ธ [3 2 0 1]`

The square brackets are used to select the first N elements from the array of indices.

You can also use a negative step to use the `numpy.argsort()`

method in
descending order.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr.argsort()) # ๐๏ธ [1 0 2 3] print(arr.argsort()[::-1]) # ๐๏ธ [3 2 0 1]`

The code for this article is available on GitHub

The negative step is used to reverse the array of indices.

The syntax for array slicing is
`arr[start:stop:step]`

.

We omitted the

`start`

and `stop`

values and only specified a negative step to reverse the array.If you need to select the indices of the highest N elements, use the following code sample.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr.argsort()) # ๐๏ธ [1 0 2 3] print(arr.argsort()[::-1]) # ๐๏ธ [3 2 0 1] print(arr.argsort()[::-1][:2]) # ๐๏ธ [3 2] print(arr.argsort()[::-1][:3]) # ๐๏ธ [3 2 0] print(arr.argsort()[::-1][:4]) # ๐๏ธ [3 2 0 1]`

The first set of square brackets `[]`

reverses the array of indices and the
second set selects the first N elements from the indices array.

This approach is a bit easier to read if you are familiar with array slicing.

Using a negative step is a little faster than negating the array.

You can imagine that the `[::-1]`

part of the code sample simply reverses the
indices array.

You can also use the
numpy.flip
method to use the `numpy.argsort()`

method in descending order.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr.argsort()) # ๐๏ธ [1 0 2 3] print(np.flip(np.argsort(arr))) # ๐๏ธ [3 2 0 1]`

The code for this article is available on GitHub

The `numpy.flip()`

method reverses the order of the elements in an array along
the given axis.

The default axis flips over all of the axes of the input array.

If you need to select the indices of the highest N elements, use the following code sample.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr.argsort()) # ๐๏ธ [1 0 2 3] print(np.flip(np.argsort(arr))) # ๐๏ธ [3 2 0 1] print(np.flip(np.argsort(arr))[:2]) # ๐๏ธ [3 2] print(np.flip(np.argsort(arr))[:3]) # ๐๏ธ [3 2 0] print(np.flip(np.argsort(arr))[:4]) # ๐๏ธ [3 2 0 1]`

`numpy.argsort()`

in descending order by multiplying by `-1`

You can also multiply each element in the array by `-1`

to use `numpy.argsort()`

in descending order.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr.argsort()) # ๐๏ธ [1 0 2 3] print((-1 * arr).argsort()) # ๐๏ธ [3 2 0 1]`

The code for this article is available on GitHub

Make sure to wrap the multiplication by `-1`

in parentheses as shown in the code
sample.

Multiplying by `-1`

simply negates the array.

main.py

`import numpy as np arr = np.array([4, 1, 5, 7]) print(arr * -1) # ๐๏ธ [-4 -1 -5 -7]`

This code sample is very similar to the one from the first subheading, however, it is less performant.

You can learn more about the related topics by checking out the following tutorials:

- AttributeError module 'numpy' has no attribute array or int
- NumPy RuntimeWarning: divide by zero encountered in log10
- ValueError: x and y must have same first dimension, but have shapes
- SystemError: initialization of _internal failed without raising an exception
- TypeError Invalid comparison between datetime64[ns] and date
- How to replace None with NaN in Pandas DataFrame
- You are trying to merge on int64 and object columns [Fixed]
- Could not broadcast input array from shape into shape [Fix]
- ValueError: object too deep for desired array [Solved]
- Only one element tensors can be converted to Python scalars
- Copy a column from one DataFrame to another in Pandas
- How to use numpy.argsort in Descending order in Python
- Object arrays cannot be loaded when allow_pickle=False
- TypeError: cannot pickle '_thread.lock' object [Solved]
- ufunc 'add' did not contain loop with signature matching types
- ValueError: Found array with dim 3. Estimator expected 2
- Input contains infinity or value too large for dtype(float64)
- RuntimeWarning: overflow encountered in exp [Solved]
- ValueError: columns overlap but no suffix specified [Solved]
- Columns have mixed types. Specify dtype option on import
- Arrays used as indices must be of integer (or boolean) type
- Finding the Range of NumPy Array elements in Python
- How to Multiply two or more Columns in Pandas
- Add columns of a different Length to a DataFrame in Pandas
- How to swap two DataFrame columns in Pandas
- Calculate the average (mean) of 2 NumPy arrays
- Check if a List is Sorted (ascending/descending) in Python