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?
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.
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.
NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument.
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.
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]]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With