Python,numpy 排序数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14875248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, numpy sort array
提问by user2046488
I'am using numpy and have an array (ndarray type) which contain some values. Shape of this array 1000x1500. I reshaped it
我正在使用 numpy 并有一个包含一些值的数组(ndarray 类型)。此阵列的形状为 1000x1500。我重塑了它
brr = np.reshape(arr, arr.shape[0]*arr.shape[1])
when I trying
当我尝试
brr.reverse()
AttributeError: ‘numpy.ndarray' object has no attribute ‘reverse'
get error. How I can sort this array ?
得到错误。我如何对这个数组进行排序?
采纳答案by Thorsten Kranz
If you just want to reverse it:
如果你只是想扭转它:
brr[:] = brr[::-1]
Actually, this reverses along axis 0. You could also revert on any other axis, if the array has more than one.
实际上,这沿轴 0 反转。如果阵列有多个轴,您也可以在任何其他轴上反转。
To sort in reverse order:
要以相反的顺序排序:
>>> arr = np.random.random((1000,1500))
>>> brr = np.reshape(arr, arr.shape[0]*arr.shape[1])
>>> brr.sort()
>>> brr = brr[::-1]
>>> brr
array([ 9.99999960e-01, 9.99998167e-01, 9.99998114e-01, ...,
3.79672182e-07, 3.23871190e-07, 8.34517810e-08])
or, using argsort:
或者,使用 argsort:
>>> arr = np.random.random((1000,1500))
>>> brr = np.reshape(arr, arr.shape[0]*arr.shape[1])
>>> sort_indices = np.argsort(brr)[::-1]
>>> brr[:] = brr[sort_indices]
>>> brr
array([ 9.99999849e-01, 9.99998950e-01, 9.99998762e-01, ...,
1.16993050e-06, 1.68760770e-07, 6.58422260e-08])
回答by Hima
Try this for sorting in descending order ,
试试这个按降序排序,
import numpy as np
a = np.array([1,3,4,5,6])
print -np.sort(-a)
回答by rafaelvalle
To sort a 1d array in descending order, pass reverse=True to sorted.
As @Erikpointed out, sortedwill first make a copy of the list and then sort it in reverse.
要按降序对一维数组进行排序,请将 reverse=True 传递给sorted。正如@Erik指出的那样,sorted将首先制作列表的副本,然后将其反向排序。
import numpy as np
import random
x = np.arange(0, 10)
x_sorted_reverse = sorted(x, reverse=True)

