Numpy Argsort - What Is It Doing

Numpy argsort - what is it doing?

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.

Example in np.argsort document

From the docs, the first line states "Returns the indices that would sort an array." Hence if you want the positions of the sorted values we have:

x = np.array([3, 1, 2])
np.argsort(x)
>>>array([1, 2, 0])

here we want the index positions of 1, 2 and 3 in x. The psotion of 3 is 0, the psotion of 1 is 1, and the position of 2 is 2, hence array([1, 2, 0]) = sorted_array(1,2,3).

Again from the notes, " argsort returns an array of indices of the same shape as a that index data along the given axis in sorted order."

A more intuitive way of looking at what that means is to use a for loop, where we loop over our returned argsort values, and then index the initial array with these values:

x   = np.array([3, 1, 2])
srt_positions = np.argsort(x)

for k in srt_positions:
print x[k]

>>> 1, 2, 3

NumPy - descending stable arg-sort of arrays of any dtype

I think this formula should work:

import numpy as np
a = np.array([1, 2, 2, 3, 3, 3])
s = len(a) - 1 - np.argsort(a[::-1], kind='stable')[::-1]
print(s)
# [3 4 5 1 2 0]

How make np.argsort place empty strings at the END of an array instead of at the beginning

One simple way of getting the order you want would be using np.roll:

lst = [ "Carrot", "Star", "Beta", "Zoro" , ""]
arr = np.array(lst)
idx = np.roll(arr.argsort(),np.count_nonzero(arr))
arr[idx]
# array(['Beta', 'Carrot', 'Star', 'Zoro', ''], dtype='<U6')

Using NumPy argsort and take in 2D arrays

I don't think there is a way to use np.take without going to flat indices. Since dimensions are likely to change, you are better off using np.ravel_multi_index for that, doing something like this:

a = np.argsort(dist, axis=1)
a = np.ravel_multi_index((np.arange(dist.shape[0])[:, None], a), dims=dist.shape)

Alternatively, you can use fancy indexing without using take:

s2 = dist[np.arange(4)[:, None], a]


Related Topics



Leave a reply



Submit