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
黄舟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.argsort
method
>>> 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
迷茫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]]
为情所困2017-05-18 10:55:30
dl1.sort(axis=0)
ndarray.sort
的关键字参数axis
It 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.