Last active
March 16, 2021 08:23
-
-
Save stevenvo/e3dad127598842459b68 to your computer and use it in GitHub Desktop.
Sort array by nth column in Numpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# sort array with regards to nth column | |
arr = arr[arr[:,n].argsort()] |
Could you tell me the code if I want the decreasing order?
For example:
mat = np.array([[1,21,3],[5,4,2],[56,12,4]])
mat_sort = mat[mat[:,2].argsort()]
print(mat_sort)
Output:
[[ 5 4 2]
[ 1 21 3]
[56 12 4]]
But if I want sorting based on 3rd column in decreasing order?
You could reverse the .argsort() results:
mat_sort = mat[mat[:,2].argsort()[::-1]]
Cool, thanx
Very nice!
Could I sort all matrix columns in descending order in similar way by using argsort()?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!