Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort unsort: array(1).sort transform of array(2) -> array(3).unsort (reversed array(1).sort

How do you sort, operate on, and then unsort the result?

Assume I have a float array p1 = 0.15,0.3, 0.25, 0.12, .... It is sorted to: p2 = sort(p1). A function (operation with p2 as input) results in p3: p3 = f(p2, x, y, ...) for some function f.

How can I unsort p3 in the smartest way? (reverse of how p1 was sorted)

i.e: p4 = unsort(p3) <- p4 unsorted to same order as p1, for comparison (x-plot) with p1?

like image 922
Trond.H.H Avatar asked Mar 13 '17 19:03

Trond.H.H


2 Answers

You need a double argsort here to keep the order:

In [6]: a
Out[6]: array([5, 4, 8, 3, 6, 1, 2, 4, 9, 6])

In [7]: b=sort(a)

In [8]: b
Out[8]: array([1, 2, 3, 4, 4, 5, 6, 6, 8, 9])

In [9]: ii=a.argsort().argsort()

In [10]: c=b*b

In [11]: c
Out[11]: array([ 1,  4,  9, 16, 16, 25, 36, 36, 64, 81])

In [12]: c[ii]
Out[12]: array([25, 16, 64,  9, 36,  1,  4, 16, 81, 36])
like image 115
B. M. Avatar answered Sep 22 '22 12:09

B. M.


One way is to use numpy.argsort to find the indices that will sort your initial array. The same indices can be used to un-sort your array into its result, as follows:

a = np.array([5, 2, 4, 3, 1])
i = np.argsort(a)    # i = array([4, 1, 3, 2, 0])

# b will be the sorted version of a    
b = a[i]             # b = array([1, 2, 3, 4, 5])
# c is the function on b
c = b**2             # c = array([ 1,  4,  9, 16, 25])

# d will hold the un-sorted result
d = np.empty(a.shape)
d[i] = c             # d = array([ 25.,   4.,  16.,   9.,   1.])

But this will require that you pre-declare d before indexing.

like image 20
Praveen Avatar answered Sep 21 '22 12:09

Praveen