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. ????
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.
You cannot unsort the list but you could keep the original unsorted index to restore positions. E.g.
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] .
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With