python3.x - Is there a direct way to sort multidimensional arrays in python?
習慣沉默
習慣沉默 2017-05-18 10:53:30
0
4
646

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

習慣沉默
習慣沉默

reply all(4)
迷茫
sorted(dl1, key=lambda x: x[0])
黄舟
>>> 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

迷茫
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]]
为情所困
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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!