Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undo or reverse argsort(), python

Given an array 'a' I would like to sort the array by columns sort(a, axis=0) do some stuff to the array and then undo the sort. By that I don't mean re sort but basically reversing how each element was moved. I assume argsort() is what I need but it is not clear to me how to sort an array with the results of argsort() or more importantly apply the reverse/inverse of argsort()

Here is a little more detail

I have an array a, shape(a) = rXc I need to sort each column

aargsort = a.argsort(axis=0)  # May use this later aSort = a.sort(axis=0) 

now average each row

aSortRM = asort.mean(axis=1) 

now replace each col in a row with the row mean. is there a better way than this

aWithMeans = ones_like(a) for ind in range(r)  # r = number of rows     aWithMeans[ind]* aSortRM[ind] 

Now I need to undo the sort I did in the first step. ????

like image 212
Vincent Avatar asked Mar 20 '10 15:03

Vincent


People also ask

What does Argsort () do in Python?

In Python, the NumPy library has a function called argsort() , which computes the indirect sorting of an array. It returns an array of indices along the given axis of the same shape as the input array, in sorted order.

Can you Unsort a list in Python?

You cannot unsort the list but you could keep the original unsorted index to restore positions. E.g.

What is the difference between Argsort and sort?

sort() returns the sorted array whereas np. argsort() returns an array of the corresponding indices. The figure shows how the algorithm transforms an unsorted array [10, 6, 8, 2, 5, 4, 9, 1] into a sorted array [1, 2, 4, 5, 6, 8, 9, 10] .

How do I sort a python order in reverse?

Sort in Descending order The sort() method accepts a reverse parameter as an optional argument. Setting reverse = True sorts the list in the descending order.


1 Answers

There are probably better solutions to the problem you are actually trying to solve than this (performing an argsort usually precludes the need to actually sort), but here you go:

>>> import numpy as np >>> a = np.random.randint(0,10,10) >>> aa = np.argsort(a) >>> aaa = np.argsort(aa) >>> a # original array([6, 4, 4, 6, 2, 5, 4, 0, 7, 4]) >>> a[aa] # sorted array([0, 2, 4, 4, 4, 4, 5, 6, 6, 7]) >>> a[aa][aaa] # undone array([6, 4, 4, 6, 2, 5, 4, 0, 7, 4]) 
like image 82
Paul Avatar answered Sep 21 '22 23:09

Paul