Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have numpy argsort return an array of 2d indices?

Tags:

If we have a 1d array

arr = np.random.randint(7, size=(5)) # [3 1 4 6 2] print np.argsort(arr) # [1 4 0 2 3] <= The indices in the sorted order     

If we have a 2d array

arr = np.random.randint(7, size=(3, 3)) # [[5 2 4] # [3 3 3] # [6 1 2]] print np.argsort(arr) # [[1 2 0] # [0 1 2] # [1 2 0]] <= It sorts each row 

What I need is the 2d indices that sort this matrix in its entirety. Something like this:

# [[2 1] => 1 # [0 1] => 2 # [2 2] => 2 # . # . # . # [0 2] => 4 # [0 0] => 5 # [2 0]] => 6 

How do I get "2d indices" for the sorting of a 2d array?

like image 413
AturSams Avatar asked Jun 01 '15 15:06

AturSams


People also ask

What does NumPy Argsort return?

argsort. Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.

How do I use Argsort in NumPy?

Syntax : numpy. argsort(arr, axis=-1, kind='quicksort', order=None) Parameters : arr : [array_like] Input array. axis : [int or None] Axis along which to sort. If None, the array is flattened before sorting.

Is NumPy Argsort stable?

NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument.

What is 2D array in NumPy?

2D array are also called as Matrices which can be represented as collection of rows and columns. In this article, we have explored 2D array in Numpy in Python. NumPy is a library in python adding support for large multidimensional arrays and matrices along with high level mathematical functions to operate these arrays.


1 Answers

Apply numpy.argsort on flattened array and then unravel the indices back to (3, 3) shape:

>>> arr = np.array([[5, 2, 4], [3, 3, 3], [6, 1, 2]]) >>> np.dstack(np.unravel_index(np.argsort(arr.ravel()), (3, 3))) array([[[2, 1],         [0, 1],         [2, 2],         [1, 0],         [1, 1],         [1, 2],         [0, 2],         [0, 0],         [2, 0]]]) 
like image 144
Ashwini Chaudhary Avatar answered Sep 29 '22 11:09

Ashwini Chaudhary