Home  >  Q&A  >  body text

python3.x - Is there a direct way to sort multidimensional arrays in python?

How to sort the following array in descending order of the first column:

dl1 = numpy.array([[ 0.02598003,1.],
                   [ 0.00730082,2.],
                   [ 0.05471569,3.],
                   [ 0.02599167,4.],
                   [ 0.0544947 ,5.],
                   [ 0.00753346,6.]])

Other places on the Internet say that direct dl1.sort() will sort by the first column by default, but it doesn’t seem to work

習慣沉默習慣沉默2732 days ago647

reply all(4)I'll reply

  • 迷茫

    迷茫2017-05-18 10:55:30

    sorted(dl1, key=lambda x: x[0])

    reply
    0
  • 黄舟

    黄舟2017-05-18 10:55:30

    >>> a=np.array([[ 0.02598003,1.],
                   [ 0.00730082,2.],
                   [ 0.05471569,3.],
                   [ 0.02599167,4.],
                   [ 0.0544947 ,5.],
                   [ 0.00753346,6.]])
    >>> a.sort(0)
    >>> a
    array([[ 0.00730082,  1.        ],
           [ 0.00753346,  2.        ],
           [ 0.02598003,  3.        ],
           [ 0.02599167,  4.        ],
           [ 0.0544947 ,  5.        ],
           [ 0.05471569,  6.        ]])
    >>> 

    np.sort sorts each dimension separately

    If you want joint sorting of two-dimensional groups, use the np.argsortmethod

    >>> a=np.array([[ 0.02598003,1.],
                   [ 0.00730082,2.],
                   [ 0.05471569,3.],
                   [ 0.02599167,4.],
                   [ 0.0544947 ,5.],
                   [ 0.00753346,6.]])
    
    >>> a[a.argsort(0)[:,0]]
    array([[ 0.00730082,  2.        ],
           [ 0.00753346,  6.        ],
           [ 0.02598003,  1.        ],
           [ 0.02599167,  4.        ],
           [ 0.0544947 ,  5.        ],
           [ 0.05471569,  3.        ]])
    >>> 

    If there is a lot of data, using python’s internal sorted will reduce efficiency

    reply
    0
  • 迷茫

    迷茫2017-05-18 10:55:30

    In [1]: lst= [[0.00730082, 2.0],
       ...:  [0.05471569, 3.0],
       ...:  [0.02599167, 4.0],
       ...:  [0.0544947, 5.0],
       ...:  [0.00753346, 6.0]]
       ...:
    
    In [2]: sorted(lst, key=lambda x: x[0])
    Out[2]:
    [[0.00730082, 2.0],
     [0.00753346, 6.0],
     [0.02599167, 4.0],
     [0.0544947, 5.0],
     [0.05471569, 3.0]]

    reply
    0
  • 为情所困

    为情所困2017-05-18 10:55:30

    dl1.sort(axis=0)

    ndarray.sort的关键字参数axisIt is used to sort by a certain column

    axis : int, optional

    Axis along which to sort. Default is -1, which means sort along the last axis.

    reply
    0
  • Cancelreply