Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, numpy sort array

Tags:

python

numpy

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 trying

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

get error. How I can sort this array ?

like image 633
user2046488 Avatar asked Feb 14 '13 12:02

user2046488


People also ask

How to sort an array in Python?

Giving arrays to an ordered sequence is called sorting. An ordered sequence can be any sequence like numeric or alphabetical, ascending or descending. Python’s Numpy module provides two different methods to sort a numpy array.

How to reverse the Order of a sorted array in NumPy?

You can see that the numpy sort () function doesn’t come which an explicit argument for sorting the array in ascending or descending order. By default, it sorts the array in ascending order. But you can use slicing to reverse the order of a sorted array.

How to sort a one-dimensional NumPy array in Python?

We can use the numpy ndarray sort () function to sort a one-dimensional numpy array. In the above example, you can see that numpy array arr gets sorted in-place, that is, the original array gets modified when using the numpy ndarray sort () function.

What are the arguments to the NumPy sort () function?

Customizations in the numpy sort function The numpy ndarray sort () and the numpy sort () function take additional arguments – axis, kind, and order. axis: The axis along which to sort the array. Defaults to -1, that is, sort along the last axis. kind: The sorting algorithm to use.


1 Answers

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])
like image 186
Thorsten Kranz Avatar answered Sep 21 '22 01:09

Thorsten Kranz