Python,numpy 排序数组

问题描述 投票:0回答:3

我正在使用 numpy 并有一个包含一些值的数组(ndarray 类型)。该数组的形状为 1000x1500。我重新塑造了它

brr = np.reshape(arr, arr.shape[0]*arr.shape[1])

当我尝试时

brr.reverse()

我收到以下错误:

AttributeError: ‘numpy.ndarray’ object has no attribute ‘reverse’

如何对这个数组进行排序?

python numpy
3个回答
30
投票

如果您只是想反转它:

brr[:] = brr[::-1]

实际上,这会沿着轴 0 反转。如果数组有多个轴,您也可以在任何其他轴上反转。

按相反顺序排序:

>>> 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])

或者,使用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])

16
投票

尝试按降序排序,

import numpy as np
a = np.array([1,3,4,5,6])
print -np.sort(-a)

4
投票

要按降序对一维数组进行排序,请将reverse=True传递给

sorted
。 正如 @Erik 所指出的,
sorted
将首先复制列表,然后反向排序。

import numpy as np
import random
x = np.arange(0, 10)
x_sorted_reverse = sorted(x, reverse=True)
© www.soinside.com 2019 - 2024. All rights reserved.