7

I'am using numpy and have an array (ndarray type) which contain some values. Shape of this array 1000x1500. I reshaped it

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

when I try

brr.reverse()

I get the following error:

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

How I can sort this array ?

3
  • what are you expecting reverse() to do? Commented Feb 14, 2013 at 12:52
  • 2
    Doesn't solve your problem, but to make your code a little neater and more efficient you can use arr.size instead of arr.shape[0]*arr.shape[1]. Commented Feb 14, 2013 at 12:59
  • I want to sort it descending. Btw sort() give the same error Commented Feb 14, 2013 at 13:12

3 Answers 3

30

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.

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:

>>> 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])
Sign up to request clarification or add additional context in comments.

3 Comments

No, it is unsorted, I have to sort it descending
Thanks! Tried argsort() with no luck. Did not knew about [::-1]
brr = np.sort(brr)[::-1]
16

Try this for sorting in descending order ,

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

Comments

4

To sort a 1d array in descending order, pass reverse=True to sorted. As @Erik pointed out, sorted will first make a copy of the list and then sort it in reverse.

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

2 Comments

sorted uses python's iterable sort, which will first copy all of the data into a list and then do the sort in reverse. While this does indeed result in a reverse sorting of the data, it doesn't do so in numpy, and generally removes any benefit of using numpy.
Thanks for sharing this, Erik. I added it to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.