Python numpy sort array

I use numpy and have an array (type ndarray) that contains some values. The shape of this array is 1000x1500. I changed it.

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

when i try

 brr.reverse() AttributeError: 'numpy.ndarray' object has no attribute 'reverse' 

get an error. How can I sort this array?

+6
source share
3 answers

If you just want to change it:

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

Actually, this changes to axis 0. You can also return to any other axis if the array has more than one.

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:

 >>> 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]) 
+23
source

Try this to sort in descending order,

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

To sort the 1st array in descending order, go backward = True to sorted . As @Erik noted, sorted will first make a copy of the list, and then sort it in reverse order.

 import numpy as np import random x = np.arange(0, 10) x_sorted_reverse = sorted(x, reverse=True) 
+2
source

All Articles