Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorted indexes in Julia (equivalent to numpy's argsort)

Tags:

julia

Which Julia's function returns the indexes that would sort an array? Python's Numpy uses argsort.

like image 617
user3639782 Avatar asked Sep 26 '16 08:09

user3639782


People also ask

How do you find the index of a sorted array?

You sort the list by passing it to sorted and specifying a function to extract the sort key (the second element of each tuple; that's what the lambda is for. Finally, the original index of each sorted element is extracted using the [i[0] for i in ...] list comprehension.

How does Argsort sort?

Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

Is NP Argsort stable?

NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument.

How do I get the indices of sorted array NumPy?

We can get the indices of the sorted elements of a given array with the help of argsort() method. This function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword.


2 Answers

julia> r = rand(0:9, 5)
5-element Array{Int64,1}:
 5
 0
 6
 1
 1

julia> i = sortperm(r)
5-element Array{Int64,1}:
 2
 4
 5
 1
 3

julia> r[i]
5-element Array{Int64,1}:
 0
 1
 1
 5
 6
like image 62
DNF Avatar answered Sep 23 '22 06:09

DNF


Im not 100% I understand the question, but I suspect that what you are asking, is that if you have the vector

a = [4,8,2]

you would like to get

order = [2,3,1]

If that's what you need, what I do is I use sortcols, which is a veird workaround

If you have a vector,

a = [5,2,8,4,3,1]

you create a new

b = hcat(a, 1:length(a))

 5  1
 2  2
 8  3
 4  4
 3  5
 1  6

then you call

c = sortrows(b, by = x -> x[1])

 1  6
 2  2
 3  5
 4  4
 5  1
 8  3

and now c[:,2] will be the latter column

 6
 2
 5
 4
 1
 3

Ofcourse, this can all be compressed into

sortrows(hcat(a, 1:length(a)), by = x -> x[1])[:,2]

but I felt like explaining how it works

Im really hoping someone posts a better way to do this, if one exists

like image 29
isebarn Avatar answered Sep 24 '22 06:09

isebarn