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

后端 未结 3 1267
星月不相逢
星月不相逢 2021-01-18 03:50

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

相关标签:
3条回答
  • 2021-01-18 04:40

    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.

    0 讨论(0)
  • 2021-01-18 04:46

    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])
    
    0 讨论(0)
  • 2021-01-18 04:46

    To unsort a list in python using built in 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 讨论(0)
提交回复
热议问题