How to sort unsort: array (1) .sort transform of array (2) & # 8594; array (3) .unsort (reverseed array (1) .sort

How do you sort, operate, and then print the result?

Suppose I have a floating point array p1 = 0.15,0.3, 0.25, 0.12, ... It is sorted by address: p2 = sort(p1) . The function (operation with p2 as input) leads to p3 : p3 = f(p2, x, y, ...) for some function f .

How can I cancel p3 the smartest way? (reverse sort p1 )

ie: p4 = unsort(p3) <- p4 unsorted in the same order as p1 , for comparing (x-plot) with p1 ?

+5
source share
3 answers

To maintain order you will need a double argument:

 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]) 
+2
source

One way is to use numpy.argsort to find the indexes that will sort your initial array. The same indexes can be used to sort the array as a result of it 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 ab = 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 a preliminary declaration of d before indexing.

0
source

To undo a list in python using inline functions:

Program:

 a=[589,273,981,642,702,883,319,128] print("a",a) b=[(p[1],p[0]) for p in enumerate(a)] print("b",b) c=sorted(b) print("c",c) d=[p[1] for p in c] z=[p[0] for p in c] print("d",d) print("z",z) y=zip(d,z) print("y",y) x=list(y) print("x",x) w=sorted(x) print("w",w) v=[p[1] for p in w] print("v",v) # unsort of z in one statement: u=[r[1] for r in sorted(list(zip([q[1] for q in sorted([(p[1],p[0]) for p in enumerate(a)])],z)))] 

Output:

 a [589, 273, 981, 642, 702, 883, 319, 128] b [(589, 0), (273, 1), (981, 2), (642, 3), (702, 4), (883, 5), (319, 6), (128, 7)] c [(128, 7), (273, 1), (319, 6), (589, 0), (642, 3), (702, 4), (883, 5), (981, 2)] d [7, 1, 6, 0, 3, 4, 5, 2] z [128, 273, 319, 589, 642, 702, 883, 981] y <zip object at 0x035E38A0> x [(7, 128), (1, 273), (6, 319), (0, 589), (3, 642), (4, 702), (5, 883), (2, 981)] w [(0, 589), (1, 273), (2, 981), (3, 642), (4, 702), (5, 883), (6, 319), (7, 128)] v [589, 273, 981, 642, 702, 883, 319, 128] u [589, 273, 981, 642, 702, 883, 319, 128] 
0
source

Source: https://habr.com/ru/post/1265402/


All Articles